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

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.

Related

ArrayList constructor accepting Collection

I have a simple question.
Lets say we have a Map, for example a Map<String, Object>
I want a method that returns a list of all values inside the Map.
The approach i use is the following:
I create a List<Object> myList = new ArrayList<>();
Get an iterator from the value set of the Map.
For each element inside the iterator i put a reference in the myList list.
Return the list
...later for each element i use i wrap it inside a synchronized block because the list contains references.
Now i am woring about using an easier apporach. The one i mean is the following:
return new ArrayList(myMap.values());
As you see in this case i simply use the constructor of the List interface which accepts a Collection.
And finally my question is:
If i use the second approach do i still get references or it copies the value objects that are inside the map?
In both cases you will get "shallow" copy of collecion, so both arrays will keep references to the same objects.
return new ArrayList(myMap.values()) will return an ArrayList containing the references of the original values of the Map. No copies of the values instances are created.
Note that if your Map contains duplicate values (i.e. values that are equal to each other), your ArrayList will also contain duplicate values. If you want to eliminate the duplicates, you should create a Set of the values instead of a List.
In either case you'll get a copy of the reference (so called "shallow copy").
There is no deep-copying (creating a completely new object with meaningfully equivalent fields -- also deep-copied) involved.

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.

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

Java generic collections

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

Not specifying which list implementation

I have a doubt considering changing this :
List<String> elements = new ArrayList<String>();
elements = elementDao.findElementsById(elementId);
to
List<String> elements;
elements = elementDao.findElementsById(elementId);
(I'm using DAO with Hibernate)
Can this cause any errors or exceptions (the fact that i'm not specifying which List implementation should be returned) ?
The first one creates a new arraylist for nothing. The created list is just garbage that has to be collected.
The second one is better, but should be reduced to
List<String> elements = elementDao.findElementsById(elementId);
You seem to be thinking that the assignment operator could be used to fill a list created by the caller. This is not the case. the assignment operator just takes the reference to the list created by the DAO (and which could be any kind of List), and assigns this reference to the variable.
You can safely change it because:
List<String> elements = new ArrayList<String>();
creates a new ArrayList and assigns it to elements, then
elements = elementDao.findElementsById(elementId);
throws the original ArrayList away (and marks it to be garbage collected) and assign elements to it the List created inside elementDao, so the second approach is just as safe and more efficient.

Categories

Resources