aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Collections - Arrays.asList() / List.add() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Collections - Arrays.asList() / List.add()" Watch "Collections - Arrays.asList() / List.add()" New topic
Author

Collections - Arrays.asList() / List.add()

Masood Alam
Greenhorn

Joined: Jul 12, 2007
Posts: 8
The below code compiles fine, however I am getting runtime exception
at Line 12...

Iam trying to insert an element of type Integer into a List<Integer>

Why is an "UnsupportedOperationException" being generated...

/********************CODE********************************************/
import java.util.*;

public class TestAsList{

public static void main(String[] args){

Integer[] arr =new Integer[] {12,34,56,78,98,23};


List<Integer> aList = Arrays.asList(arr);

aList.add(new Integer(1232)); //Line 12

System.out.println("Printing aList :" + aList);

}

}

//*********************output***************************************/

Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:131)
at java.util.AbstractList.add(AbstractList.java:91)
at TestAsList.main(TestAsList.java:12)
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 39547
    
  27
The java docs for Arrays.asList say that "Returns a fixed-size list backed by the specified array." If you want a modifiable list you can do something like "ArrayList anotherList = new ArrayList(aList)".


Ping & DNS - updated with new look and Ping home screen widget
Masood Alam
Greenhorn

Joined: Jul 12, 2007
Posts: 8
Thanks it works...

However I do still have the same doubt, as per the documentation

Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)

Does this mean we cannot change the list..then how will it change the array as per the line "(Changes to the returned list "write through" to the array.)"
Manfred Klug
Ranch Hand

Joined: Jun 04, 2007
Posts: 377
Originally posted by Masood Alam:
Does this mean we cannot change the list
You cannot change the size of the list. But you can do the following:
Masood Alam
Greenhorn

Joined: Jul 12, 2007
Posts: 8
Thank you !!!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Collections - Arrays.asList() / List.add()
 
Similar Threads
NullpointerException in Arrays.sort()
Arrays.toArray : All my knowledge collapses ...
Question? int[] Vs Integer[]
Using asList with Generics
Collections :List.add throws runtime Exception(Unsupported Exceptions)