• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

retainAll() method in java.util.AbstractCollection Interface

 
Emir Qureshi
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I Observed the weird behavior of retailAll() method in AbstractCollection Interface.

Here's the piece of code i was working on, Defining an Integer array and calling asList on the Arrays to obtain the equivalent content List.

Integer arrint[]={1,2,3,4};
Integer newarrint[] = {1,2,3};
List<Integer> al = new ArrayList<Integer>() ;

List<Integer> nal = new ArrayList<Integer>();
al = Arrays.asList(arrint);
System.out.println("al: "+al);
alr = Arrays.asList(newarrint);
System.out.println("nal: "+nal);

System.out.println(al.retainAll(nal));
System.out.println("Modified nal: "+nal);

It throws error as mentioned

Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:144)
at java.util.AbstractList$Itr.remove(AbstractList.java:360)
at java.util.AbstractCollection.retainAll(AbstractCollection.java:370)
at CollectionsFrameworkExample.main(CollectionsFrameworkExample.java:34)


Now, I modified and added the contents in list using add() as shown below, it worked fine ... y such weird behavior.
List<Integer> al = new ArrayList<Integer>() ;
List<Integer> alr = new ArrayList<Integer>();
al.add(1);
al.add(2);
al.add(3);
al.add(4);
alr.add(1);
alr.add(2);
alr.add(3);
System.out.println("al: "+al);
System.out.println("alr: "+alr);
System.out.println(al.retainAll(alr));
System.out.println("Modified al: "+al);


Share your valuable thoughts on the same... ThankYou.




 
Paul Clapham
Sheriff
Posts: 21416
33
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My most valuable thought would be this: Read the documentation for Arrays.asList().

Its summary says this:
Returns a fixed-size list backed by the specified array.

And now you're trying to call a method on that list which might change the size of the list, by removing some elements. Obviously that wouldn't work, so calling the method isn't allowed.
 
Emir Qureshi
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul Clapham wrote:My most valuable thought would be this: Read the documentation for Arrays.asList().

Its summary says this:
Returns a fixed-size list backed by the specified array.

And now you're trying to call a method on that list which might change the size of the list, by removing some elements. Obviously that wouldn't work, so calling the method isn't allowed.



Thanks Paul.
 
Emir Qureshi
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Paul
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic