People say that asList method convert the array into list and its not copying, so every change in 'aList' will reflect into 'a'. So add new values in 'aList' is illegal, since array have fixed size.
But, asList() method returns ArrayList<T>. How the compiler differentiates line 3 from 5. Line 3 gives me exception (UnsupportedOperationException).
String[] a = {"a","b","c","d"};//1
List<String> aList = Arrays.asList(a);//2
aList.add("e");//3
List<String> b = new ArrayList<String>();//4
b.add("a");//5
This List implementation you receive from Arrays.asList is a special view on the array - you can't change it's size.
The return type of Arrays.asList() is java.util.Arrays.ArrayList which is often confused with java.util.ArrayList. Arrays.ArrayList simply shows the array as a list.
Read again, the type of Arrays.asList is:
public static <T> List<T> asList(T... a)
which clearly states that asList returns an object that implements interface java.util.List, nowhere does it says it will return an instance of class java.util.ArrayList.
Next, notice that the documentation on List.add says:
boolean add(E e)
Appends the specified element to the end of this list (optional operation).
Technically, everytime you use a variable typed as List (instead of ArrayList), you should always be careful to expect that this method may throw UnsupportedOperationException. If you are sure that you will only receive a List implementation that always have the correct semantic of .add(), then you can omit the check at the risk of a bug when your assumption is invalidated.
Manoj,
The Return type of Arrays.List is some unknown internal implementation of the List interface and not java.util.ArrayList, so you can assign it only to a List type.
If you assign it to an ArrayList for instance it will give you compile time error
"Type mismatch: cannot convert from List to ArrayList"
ArrayList<String> aList = Arrays.asList(a);// gives Compile time error
From the Javadoc "Arrays.asList Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) " that means that you are only provided a list view of the Array which IMO is created at runtime and ofcourse you cannot change the size of an array so you can't change size of "Arrays.asList" also.
IMO the internal implementation of Arrays.asList has all the implemented methods which can change the size of the Array as -
void add(E e)
{
//some unknown code
throw(java.lang.UnsupportedOperationException);
}
so whenever you attempt to alter the size of the Array it throws the UnsupportedOperationException.
Still if you want to add some new items to an ArrayList by using such a syntax, you can do so by creating a subclass of Arraylist(preferably by using anonymous subclass of ArrayList). You can pass the return type of Arrays.List to the constructor of ArrayList, (ie. public ArrayList(Collection c)) something like this -
List<String> girlFriends = new java.util.ArrayList<String>(Arrays.asList("Rose", "Leena", "Kim", "Tina"));
girlFriends.add("Sarah");
Now you can easily add Sarah to your GF list using the same syntax.
PS - Please select this one or another one as your answer because evrything has been explained. Your low Acceptance rate is very discouraging.
asList() doesn't return a java.util.ArrayList, it returns a java.util.Arrays$ArrayList. This class doesn't even extend java.util.ArrayList, so its behaviour can be (and is) completely different.
The add() method is inherited from java.util.AbstractList, which by default just throws UnsupportedOperationException.
You're assuming that Arrays.asList() returns an ArrayList, but that's not the case. Arrays.asList() returns an unspecified List implementation. That implementaton simply throws an UnsupportedOperationException on each unsupported method.
It's an exception and not a compiler error. It is thrown when the program is run and not at the compile time. Basically the actual class that Arrays.asList will return has a throw UnsupporteOperationException inside the add() method.
To be more specific Arrays.asList will return an inner class defined inside the Arrays class that is derived from AbstractList and does not implement the add method. The add method from the AbstractList is actually throwing the exception.
The key to this is the List implementation returned by
List<String> aList = Arrays.asList(a);
If you look at the source code in Arrays you will see that it contains an internal private static class ArrayList. This is not the same as java.util.ArrayList.
asList returns a fixed-size list, so that you cannot add new elements to it. Because the list it returns is really a "view" of the array it was created from ('a' in your case), it makes sense that you won't be able to add elements - just like you can't add elements to an array. See the docs for asList
Related
This is reg. a requirement where I need to remove an element from List in java. I am getting unsupported exception when I try to remove element from List. Below is the code:
String[] str_array = {"abc","def","ght"};
List<String> results = Arrays.asList(str_array);
String tobeRemovedItem="";
for(int i=0;i<results.size();i++){
if(results.get(i).equalsIgnoreCase(searchString)) {
tobeRemovedItem=results.get(i);
}
}
if(!TextUtils.isEmpty(tobeRemovedItem)) {
results.remove(tobeRemovedItem); // I am getting exception here.
}
Can anyone help me in solving this issue?
The type of list returned by Arrays.asList does not support the remove operation. Hence the exception.
You can use the java.util.ArrayList instead.
List<String> results = new ArrayList<String>(Arrays.asList(str_array));
Answered already, but now without indirect datastructure of .asList()
List<String> results = new ArrayList<>();
Collections.addAll(results, str_array);
The .asList is backed by the array, hence you can modify the original array be modifying the list. And vice versa you cannot grow or shrink the list, as then the backed array object would need to be exchanged, as arrays are fixed in java.
The size of List returned by Arrays.asList cannot be changed. Instead you can do:
List<String> results = new ArrayList<>(Arrays.asList(str_array));
In general, UnsupportedOperationException is thrown by the implementation of an interface (or a child class of a class with an abstract method), where the implementor did not want to support that particular method.
That said, to debug these issues in the future, check which implementation you're using - in this case, it's given via the Arrays.asList() method from the Android sdk. Here you can see it says that it does not support adding or removing of items to the list.
If you must add and remove items, you can wrap the call into the ArrayList implementation of List which does support such modification (as suggested by Banthar and khelwood). The constructor takes a list as input, and copies the elements inside.
I got a method
foo(list);
that get's a
List<SomeEntit>
as input.
My method foo looks somewhat like the following:
public void foo(List<SomeEntity someEntities) {
someEntities.add(anotherEntity);
}
I then get an "javax.ejb.EJBException: java.lang.UnsupportedOperationException" caused by "java.lang.UnsupportedOperationException: null" at "at java.util.AbstractList.add(AbstractList.java:148)"
Can you tell me why this is happening? I hope that my code example is not too minimal.
Some lists are unmodifiable. The operation of adding elements is then "unsupported".
Java collections framework does not have a distinct type for unmodifiable lists or other unmodifiable collections. You never really know if it is allowed to add something.
All you can do is to specify that the list that is passed must be modifiable.
It seems that the actual type of the List you get as the input does not override the add method.
Try converting that list to a list implementation that does, like ArrayList:
List<SomeEntity> newList = new ArrayList<>(list);
foo(newList);
Arrays.asList returns a typed List. But List is an interface so how can it be instantiated? If try and instantiated a typed List I get an error saying it is not possible.
Edit
Nevermind I see what's going on, just got confused by the docs for a moment.
It's an Arrays.ArrayList which shouldn't be confused with java.util.ArrayList. It is a wrapper for the array which means any changes you make, alter the original array, and you can't add or remove entries. Often it is used in combination with ArrayList like
List<String> words = new ArrayList<>(Arrays.asList("Hello", "There", "World"));
A List can't be instantiated, sure. But you can instantiate a class which implements List -- for example, an ArrayList or LinkedList, etc. These classes really are Lists. The point of returning a List (the interface type) is that the method can return any object which implements the List interface, and you shouldn't worry about exactly which concrete type it is.
from class Arrays
public static transient List asList(Object aobj[])
{
return new ArrayList(aobj);
}
so when you execute Arrays.asList(...) you will take ArrayList which implements List. nobody will know that, except this one itself.
1 example
String[] array = new String[] {"one","two","three"};
List list = Arrays.asList(array);
I start learning the Java generic collection using Deitel Harvey book - but I am facing a difficulty understanding the three line of codes below - Do all of them perform the same operation on by intializing and adding the relevant values of array ( colors ) to the LinkList variable (list1). How does the second method and third method works - I am having a bit difficulty understanding how Arrays can viewed as a list.. As I know arrays are not dynamic data structure, they have fixed sized length, adding/ removing elements on array can not be done on running time comparing to Lists in general.
String[] colors = { "black", "white", "blue", "cyan" };
List< String > list1 = new LinkedList< String >();
// method 1 of initalizing and adding elments to the list
for (String color : colors)
list1.add(color);
// method 2 of initializing and adding elements to the list
List< String > list1 = new LinkedList< String > (Arrays.asList(colors));
// method 3 of initializing and adding elements to the list
List< String > list1 = Arrays.asList(colors);
Please help me understand my queries above, don't judge me as I am still new to this.
Thank you, Sinan
Actually knowledge of generics is not necessary for answering this question.
As you correctly identifier arrays are static in the sense that you can't add elements to them or remove them.
Lists, however, usually allow those operations.
The List returned by Arrays.asList() does have the add/remove methods (otherwise it would not be a valid List). However actually calling those methods will throw an UnsupportedOperationException exactly because you can't actually add elements to an array (for which this List is simply a view/wrapper).
Operations that don't structurally modify the list (i.e. that don't change the number of elements in the list) are entirely possible: set(int, E) works just fine on the List returned by Arrays.asList().
Arrays.asList returns a fixed-size list backed by the specified array.
It is actually a bridge between Array and Collection framework. But returned list write through to the array.
Only your first method does anything to the LinkedList you have initially assigned into list1. The other two assign a new, unrelated list to it. The third option assigns something that isn't a LinkedList, but a special implementation of the List interface backed by your String array. In the third case you won't be able to add/remove elements from the list, but you can iterate over it and update existing slots. Basically, it does what a plain array does, just through the List interface.
Arrays.asList creates a List from an Array. Arrays in general can't be viewed as lists in Java. They can only be wrapped in a list.
So method 2 is used to have a specific list implementation LinkedList in this case.
to Method 2, just check the Api here:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html#LinkedList(java.util.Collection)
For sure, Lists implement the Collections Interface so this Constructor will work here.
to Method 3, just check out the Api here: http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList(T...)
Every time you are interested in implementation you can look into certain method. For example, by press Ctrl+left mouse button onto method or class.
// method 2 of initializing and adding elements to the list
List<String> list1 = new LinkedList<String> (Arrays.asList(colors));
This code leads to:
List<String> list1 = new LinkedList<String> (new ArrayList<String>(colors));
In constructor of ArrayList:
ArrayList(E[] array) {
if (array==null)
throw new NullPointerException();
a = array;
}
the actual array is copied to encapsulated private array field(link is copied).
Then in constructor of LinkedList:
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
Every element of passed collection is added to the LinkedList.
if you see the link below
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html#LinkedList%28java.util.Collection%29
you will see the constructor of linked list class which is accepting a collection object as parameter.
Any in your post, the 2nd and 3 rd lines are passing an object of collection class(i.e Arrays.asList is finally giving a List which is a sub class of collection).
So both 2nd and 3rd lines fairly valid implementations.
More over you can observe one more good coding practice in all the 3 lines.
That is
writing code to interceptors than to classes
. (referring
LinkedList
instance with
List
interface)
Always try to refer your classes with interceptors which is a good practice
I recently found out that there are actually 2 different ArrayList implementations in Java (better late than never I guess...).
So I was wondering why does Arrays.asList(T... a) need to return a list which can not be resized ? If they needed an unmodifiable list why add the set(int index, E element) method then ?
So my general question is why not return the java.util.ArrayList from the Arrays.asList(T... a) method ?
Also what do you gain with the java.util.Arrays.ArrayList implementation ?
You asked:
Also what do you gain with the
java.util.Arrays.ArrayList
implementation ?
It is because the Arrays$ArrayList returned by Arrays.asList is just a view on the original array. So when the original array is changed then the view is changed too.
If one would use an real ArrayList then the elements will be copied, and a change on the orignal array would not infuence the ArrayList.
The reasons to do this are quite simple:
performance: no need to copy anyting
memory efficent: no second array is needed
The javadoc says that asList returns "a fixed-size list backed by the specified array". If you want to resize the array, you have to create a new one and copy the old data. Than the list won't be backed by the same array instance. The stated goal is "This method acts as bridge between array-based and collection-based APIs." and so write-through to the underlying array is a design requirement.
They are two different classes with different behaviours.
The list returned when you called Arrays.asList is a thin wrapper over the array, not a copy. The list returned is fixed size: attempting to call add will throw an UnsupportedOperationException exception.
The java.util.ArrayList on the other hand keeps its own internal copy of the data and is variable sized.
Arrays.asList needs to return a list that cannot be resized -- because the underlying array cannot be resized -- but that is modifiable -- because assignment to elements in the underlying array is allowed.
actually you are able to add elements to the ArrayList with add. method like this :
List<String> l2= new ArrayList<String>(Arrays.asList(array1));
l2.add("blueCheese");
In my opinion you use it to get the features of a List but applying them to an Array .
Two comments:
1, Attempting to shrink the returned array by calling the remove() method of List interface will throw an UnsupportedOperationException. This is because the inner ArrayList class inside of Arrays class extends AbstractList, and the remove() method in AbstractList throws UnsupportedException.
Thus once the List is returned, you can overstore existing elements EITHER in the array OR in the returned List, BUT you are NOT permitted to grow the array or shrink the array.
In response to:
actually you are able to add elements to the ArrayList with add. method like this :
List l2= new ArrayList(Arrays.asList(array1));
l2.add("blueCheese");
The l2 is an independent copy of the list, so List l2 is now decoupled from the original array&List. So blueCheese in in l2, but not in the original array/List that were backed up from each other.
-dbednar