ArrayList and HashSet differs based on the following parameters:➡➡
1. Duplicate Object
ArrayList allows duplicate elements to be stored in it.
HashSet doesn’t allow duplicate element. All the element needs to be unique.
2. Order Maintenance
Being a List implementation, ArrayList maintains the insertion order.
In HashSet, insertion order is not maintained. (HashSet-> order not guaranteed, LinkedHashSet-> Order is maintained)
3. Null value
In ArrayList, one can store unlimited null values
In HashSet, only one null value is permitted.
4. Implementations
ArrayList class implements List interface.
HashSet implements Set interface.
5. Traversal
You can use both ListIterator and Iterator to traverse elements in ArrayList.
You cannot use ListIterator to iterate HashSet. To traverse HashSet use Iterator.
5. Example
ArrayList Example
package
javaRadarArrayList;
import
java.util.ArrayList;
import
java.util.Iterator;
public class
ItrTraversal {
public static void main(String[] args) {
//create Array List
ArrayList<String>
javaRadarList = new ArrayList<String>();
//Add elements to ArrayList
javaRadarList.add("Java");
javaRadarList.add("Java");
javaRadarList.add("Spring");
javaRadarList.add("Hibernate");
javaRadarList.add("EJB");
//creating iterator to traverse over
javaRadarList
Iterator<String> listIterator
= javaRadarList.iterator();
while(listIterator.hasNext()){
System.out.println(listIterator.next());
}
}
}
OUTPUT:
Java
Java // duplicate java is accepted by List
Spring
Hibernate
EJB
HashSet Example
package
javaRadarHashSet;
import
java.util.HashSet;
import
java.util.Iterator;
public class ItrTraversal {
public static void main(String[] args) {
//create Array
List
HashSet<String>
javaRadarSet = new
HashSet<String>();
//Add elements
to ArrayList
javaRadarSet.add("Java");
javaRadarSet.add("Java");
javaRadarSet.add("Spring");
javaRadarSet.add("Hibernate");
javaRadarSet.add("EJB");
//creating
iterator to traverse over javaRadarList
Iterator<String>
setIterator = javaRadarSet.iterator();
while(setIterator.hasNext()){
System.out.println(setIterator.next());
}
}
}
OUTPUT:
Java // duplicate java is not accepted by Set
Hibernate
Spring
EJB
You may also like to read:
No comments:
Post a Comment