Java generic collections - java

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

Related

Collections.singleton() methods does not work as documentation?

I have tested Collections.singleton() method, how to work, but i see that it is not work as what documentation say?
List arraylist= new ArrayList();
arraylist.add("Nguyen");
arraylist.add("Van");
arraylist.add("Jone");
List list = Collections.singletonList(arraylist);// contains three elements
System.out.println(list.size());// right
As what documentation say, The method call returns an immutable list containing only the specified object,A singleton list contains only one element and a singleton HashMap includes only one key. A singleton object is immutable (cannot be modified to add one more element),but when what thing i see in my code that list contains three elements("Nguyen","Van","Jone").
Anybody can explain for me why?? Thanks so much !!
The returned List is a List of Lists. In this case, the returned list of lists itself is immutable, not the contained List. Also the returned list contains only one element, not three: the arraylist variable itself is considered an element and is the only element stored in the list returned by Collections.singletonList. In other words, the statement Collections.singletonList(arraylist) does not create a list that contains all elements of the provided list.
It would have been much more obvious if you use generics:
List<String> arraylist= new ArrayList<>();
arraylist.add("Nguyen");
arraylist.add("Van");
arraylist.add("Jone");
List<List<String>> list = Collections.singletonList(arraylist);
What the documentation says is that if you do the following:
List list = Collections.singletonList(arraylist);
list.add(new ArrayList());
then this would throw an exception at runtime.

how to remove element from List in java

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.

API java List and Collection [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
what does it mean
it's a array or it's a list type string
List<String> list = new ArrayList<String>(); // why parenthesis
List<String> removeList = new ArrayList<String>();//why parenthesis
and this method
so What is the deference between List and Collection and arrys
// what mean this collection
private void removeColors(Collection<String> collection1,Collection<String> collection2)
{
Iterator<String> iterator = collection1.iterator();//what does mean
while(iterator.hasNext())//what does mean
if(collection2.contains(iterator.next()))//what does mean
iterator.remove();//what does mean
}
You should read documentation about collections.
http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html
A Collection is - a collection of data. This is the base interface for any kind of collection (list, map, tree, ...). Any collection is (or should be) Iterable, that means that you can iterate through all the elements of a collection (for example, in a loop).
A List is obviously a collection as well, since a list is a collection of data. That's why the List interface extends the Collection interface.
However, since there are lots of ways to implement a List, List is merely an interface rather than a class. ArrayList implements a list by wrapping an array. Another example would be LinkedList, which stores data by linking the elements to each other. I don't want to discuss their advantages and disadvantages (as you can look them up).
The last thing to consider is the fact that the data you store inside a collection (a list) has a type. Usually, you will only store one type of Object inside a specific collection, which is why the Collection interface (and all of its subinterfaces like List) take a type parameter. This parameter specifies the type of data you would like to store in your list which is good for type safety and convenience.
Now, in your code:
List<String> list = new ArrayList<String>();
List<String> removeList = new ArrayList<String>();
You create a variable called "list". The type of this variable is List<String>, which means: a list of strings. With the new operator, you create the actual object. Obviously, you have to choose an implementation, and you chose "ArrayList". Naturally, you want Strings in your collection, so you specify String as the type parameter. Since you are calling ArrayList's constructor, you need empty parenthesis (so you call the constructor that doesn't take any arguments).
The second line of code does the same.
//this method takes two collections
//that means that you can pass any type of collection (including list) to it
//the advantage is that you could also pass another type of collection if you chose to do so
private void removeColors(Collection<String> collection1,Collection<String> collection2)
{
Iterator<String> iterator = collection1.iterator();//this line takes the iterator of your first collection
//an iterator is an object that allows you to go through a collection (list)
//you can get the objects one by one by calling the next() method
while(iterator.hasNext())//basically, that's what you're doing here:
//you let the loop continue as long as there are more items inside the iterator, that is, the first collection
if(collection2.contains(iterator.next()))//so if there's another item, you take it by calling next() and check if the second collection contains it
iterator.remove();//if that's the case, you remove the item from the first collection
}
//what you've basically achieved:
//you removed all the items from the first collection that you can find in the second collection as well, so you could say:
//collection1 = collection1 - collection2
Now, you could fill the list of strings you created above with data (strings) and do the same with removeList, and then "subtract" removeList from list by calling:
removeColors(list, removeList);
In Java an array has got a specific size that can't be changed. If you come from other scripting languages like php this may be new to you.
That's why for example ArrayLists are often used. You got a dynamic size where you can add and remove elements as you want.
List<String> tells your compiler that only Strings are accepted ( https://en.wikipedia.org/wiki/Type_safety ).
A List is a specialization of a Collection.
Type Parameters:
E - the type of elements in this list
All Superinterfaces:
Collection, Iterable
source: http://docs.oracle.com/javase/7/docs/api/java/util/List.html
more information:
http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html
explained below
List<String> list = new ArrayList<String>(); // to call constructor for creating Arraylist of type String
List<String> removeList = new ArrayList<String>(); // same as above
private void removeColors(Collection<String> collection1,Collection<String> collection2)
{
Iterator<String> iterator = collection1.iterator();//to get typesafe iterator of underlying collection
while(iterator.hasNext())//to check if there is another element in collection
if(collection2.contains(iterator.next()))
//interator.next() - to get next String from collection
//collection2.contains(..) - to check if String already presents in another collection
iterator.remove();//remove element from iteration and move to next element
}

How can Arrays.asList return an instantiated List?

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);

Why does Arrays.asList() return its own ArrayList implementation

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

Categories

Resources