JNL
JNL

Reputation: 4703

UnSupported Exception in ArrayList

I was implementing a program to remove the duplicates from the 2 character array. I implemented these 2 solutions, Solution 1 worked fine, but Solution 2 given me UnSupportedOperationException. Why is that so? The error is at line al1.removeAll(al2);

public void getDiffernce(Character[] inp1, Character[] inp2){

    // SOLUTION 1:
    // **********************************************

    List<Character> list1 = new ArrayList<Character>(Arrays.asList(inp1));
    List<Character> list2 = new ArrayList<Character>(Arrays.asList(inp2));
    list1.removeAll(list2);

    System.out.println(list1);
    System.out.println("***************************************");


    // SOLUTION 2:

    Character a[] = {'f', 'x', 'l', 'b', 'y'};
    Character b[] = {'x', 'b','d'};

    List<Character> al1 = new ArrayList<Character>(); 
    List<Character> al2 = new ArrayList<Character>(); 
    al1 = (Arrays.asList(a)); System.out.println(al1);
    al2 = (Arrays.asList(b)); System.out.println(al2);  
    al1.removeAll(al2);         // error is here     
    System.out.println(al1);
}

Upvotes: 0

Views: 554

Answers (3)

nanofarad
nanofarad

Reputation: 41271

Arrays.asList() returns a fixed-size list. No entries can be added or removed.

You can work around this by:

al1 = new ArrayList<Character>((Arrays.asList(a))); 

and the same for al2.

This is already happening in the top solution.

in the second, you create an ArrayList then overwrite it with the fixed one, instead of filling it, keeping in mutable.

Upvotes: 3

fge
fge

Reputation: 121712

You use Arrays.asList(). And this type of list is not modifiable.

The javadoc explicitly says so:

Returns a fixed-size list backed by the specified array. [emphasis mine]

Upvotes: 0

Jack
Jack

Reputation: 133567

From the asList(..) documentation:

Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess.

Basically the asList method does not create a normal mutable List<E> but a wrapper around an array. The remove operation is hence not available on a list which is backed by an array.

Try to build your lists by manually constructing them:

List<Character> al1 = new ArrayList<Character>(Arrays.asList(a)) 

So that the backed list is used only to initialize a real ArrayList.

Upvotes: 3

Related Questions