File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Masood Alam
Greenhorn
Posts: 8
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Pie
Posts: 42966
73
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)".
 
Masood Alam
Greenhorn
Posts: 8
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 377
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you !!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic