What is the result?

Given the code fragment:

public class Rank {

static CopyOnWriteArraySet<String> arr = new CopyOnWriteArraySet<>();

static void verify() {

String var =””;

Iterator<String> e=arr.iterator();

while (e.hasNext()) {

var = e.next();

if(var.equals(“A”))

arr.remove(var);

}

}

public static void main (String[] args) {

ArrayList<String> list1 = new ArrayList<>();

list1.add(“A”); list1.add(“B”);

ArrayList<String> list2 = new ArrayList<>();

list1.add(“A”); list1.add(“D”);

arr.addAll(list1);

arr.addAll(list2);

verify();

for(String var : arr)

System.out.print(var + ” “);

}

}

What is the result?

Given the code fragment:

public class Rank {

static CopyOnWriteArraySet<String> arr = new CopyOnWriteArraySet<>();

static void verify() {

String var =””;

Iterator<String> e=arr.iterator();

while (e.hasNext()) {

var = e.next();

if(var.equals(“A”))

arr.remove(var);

}

}

public static void main (String[] args) {

ArrayList<String> list1 = new ArrayList<>();

list1.add(“A”); list1.add(“B”);

ArrayList<String> list2 = new ArrayList<>();

list1.add(“A”); list1.add(“D”);

arr.addAll(list1);

arr.addAll(list2);

verify();

for(String var : arr)

System.out.print(var + ” “);

}

}

What is the result?

A.
Null B D

B.
Null B null D

C.
B D

D.
D

E.
An exception is thrown at runtime



Leave a Reply 3

Your email address will not be published. Required fields are marked *


Serg

Serg

It’s have not correct antvort. arr is EMPTY after function verify().

arr.size() BEFORE verify() is :3
arr.size() AFTER verify() is :0

Serg

Serg

I’m Sorry. lost “if(var.equals(“A”))”

Corect answer is “C”.

=============================== Start F029 =====================================
arr.size() BEFORE verify() is :3
arr.size() AFTER verify() is :2
var is :B
var is 😀
=============================== END F029 =====================================

Tim

Tim

Yes the answer is C (output “B D”).

However, if we change arr.remove(var) to e.remove(), the answer will be E (throws UnsupportedOperationException). This is because the Iterator of CopyOnWriteArraySet / CopyOnWriteArrayList does not support remove() operation.