Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning ArrayList to List [duplicate]

Tags:

java

Is there any Difference between two lines in the following

 ArrayList<String> arrName =  new ArrayList<String>();
 List<String>      arrName =  new ArrayList<String>();

Thanks for Reply

like image 575
Java Beginner Avatar asked Feb 20 '13 07:02

Java Beginner


People also ask

Can ArrayList hold duplicates?

ArrayList allows duplicate values while HashSet doesn't allow duplicates values. Ordering : ArrayList maintains the order of the object in which they are inserted while HashSet is an unordered collection and doesn't maintain any order.

How do you add duplicate elements to an ArrayList in Java?

collect(Collectors. toList()); This code says for each member of the list turn it into 4 copies of the item then collect all those as a list and add them to the original list.

How do you avoid duplicates in an ArrayList?

The easiest way to remove repeated elements is to add the contents to a Set (which will not allow duplicates) and then add the Set back to the ArrayList : Set<String> set = new HashSet<>(yourList); yourList. clear(); yourList.

How do I copy an ArrayList to another list?

In order to copy elements of ArrayList to another ArrayList, we use the Collections. copy() method. It is used to copy all elements of a collection into another. where src is the source list object and dest is the destination list object.


1 Answers

Almost always the second one is preferred over the first one. The second has the advantage that the implementation of the List can change (to a LinkedList for example), without affecting the rest of the code. This is will be difficult to do with an ArrayList, not only because you will need to change ArrayList to LinkedList everywhere, but also because you may have used ArrayList specific methods.

like image 161
Rahul Avatar answered Oct 25 '22 16:10

Rahul