API java List and Collection [closed] - java

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
}

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.

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.

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

Iterator and iteratorList with synchronization in java

i have an arraylist and i want to add and remove many items at he same(almost) time. So i decide to create 2 methods. In the first method i implement the method which contains the remove part i use something like:
//my list
ArrayList<Human> list= new ArrayList<Human>(100);
//Human is the object of the class Human
List<Human> syncList = Collections.synchronizedList(new ArrayList<Human>());
synchronized (syncList){
for (Iterator<Human> iter = list.iterator(); iter.hasNext();) {
Human = iter.next();
-
-
//using the removes method of the iterator
it.removes(something);
And in the second method (which i need to add many items) something like this:
for( ListIterator<Human> it = list.listIterator();it.hasNext();){
List<Human> syncList = Collections.synchronizedList(newArrayList<Human>());
synchronized (syncList){
-
-
//using the add method of the iterator list
it.add(something)
Now i realize that when those two void methods finished and the list called by another function don't have the appropriate behaviour. I mean that some of the elements didn't add or removed from the list. How can i fix this?any ideas?
you are synchronizing on 2 entirely different objects, hence the inconsistent behavior. your call to synchronizedList() is returning a wrapper around the original list, on which you are synchronizing. since the 2 methods are using different wrappers, no actual synchronization is happening. you just need to synchronize on the original list implementation. of course, any other usage of the list member should also be synchronized.

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