HI,

From the following code:

1 import java.util.*;
  2 
  3 public class t2 {
  4         public static void main(String[] args) {
  5                 List aList = new ArrayList();
  6 
  7                 aList.add("a");
  8                 aList.add("b");
  9                 aList.add("c");
 10                 aList.add("d");
 11 
 12                 List bList = new ArrayList();
 13 
 14                 bList.add(aList.get(1));
 15                 bList.add(aList.get(3));
 16 
 17                 aList.remove(bList);
 18 
 19                 System.out.println("aList[0] = "+aList.get(0));
 20                 System.out.println("aList[1] = "+aList.get(1));
 21 
 22                 for (int i = 0;i < bList.size();i++) {
 23                         System.out.println("b["+i+"]="+bList.get(i));
 24                         aList.remove(bList.get(i));
 25                 }
 26 
 27                 for (int i = 0;i < aList.size();i++) {
 28                         System.out.println(aList.get(i));
 29                 }
 30         }
 31 }

The output is:

aList[0] = a
aList[1] = b
b[0]=b
b[1]=d
a
c

I hoped that the call aList.remove(bList) at line 17 would remove "b" and "d" from aList and the output would be

aList[0] = "a"
aList[1] = "c"

But why is it behaving so (which is counter-intuitive)? I just wanted to remove the elements in bList from aList. Otherwise I have to iterate bList and then call aList.remove(bList.get(i)) to do that (which is cumbersome).

Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.