Difference between List and Set

Difference between List and Set
List and Set are interfaces and in java.util package.
Base interface for List and Set is java.util.Collection interface.

List can store duplicate object, but Set does not store duplicate objects.

Iterator and ListIterator can be used to traverse thru the elements of List. But only Iterator can be used to
traverse thru the elements of Set.

List stores elements in the same order as they are added. But Set stores the elements in different order, than they are added.

Difference between ListIterator and Iterator

List has two different implementations, ArrayList and LinkedList. ArrayList internal implementation is based on arrays, and LinkedList internal implementation is based on linked list data structure.

Set has two different implementations, HashSet and TreeSet. HashSet internal implementation is based on hashing the elements, TreeSet is based on Red Back Tree data structure.

ArrayList example:


import java.util.*;
public class ArrayListDemo {

	public static void main(String[] args) {

	//List allows duplicate values, stores values in the order given/added
	//Dynamic Arrays, can shrink or increase size dynamically unlike normal arrays
	ArrayList al = new ArrayList();
	al.add("BCD");
	al.add(0, "A1");
	al.add("A2");
	al.add(2, "A3");
	al.add(3, "A4");

	al.add(0, "C1");

	System.out.println("ArrayList is:"+al);

	Iterator itr = al.iterator();
	//using Iterator, we can traverse only in forward direction
	for(;itr.hasNext();)
	{
	String str = (String)itr.next(); //returns Object
	System.out.println(str+" ");
	}

	ListIterator litr = al.listIterator();

	for(;litr.hasNext();)
	{
	String str = (String)litr.next(); //returns Objectr

	//using ListIterator we can traverse backward as well
	//String pstr = (String) litr.previous();

	System.out.println("Next is "+str);
	}

	System.out.println("-------------------------");

	al.remove(2);
	//Getting Array
	Object obj[] = al.toArray();

	for(int i=0;i

output:
ArrayList is:[C1, A1, BCD, A3, A4, A2]
C1
A1
BCD
A3
A4
A2
Next is C1
Next is A1
Next is BCD
Next is A3
Next is A4
Next is A2
-------------------------
C1
A1
A3
A4
A2

HashSet example:


import java.util.*;

public class SetDemo {

public static void main(String args[])
{
//stores unique values only, no guarantee in the order of objects stored
HashSet hs = new HashSet();

hs.add("to");
hs.add("test");
hs.add("random1");
hs.add("string");
hs.add("some");
hs.add("random1");

System.out.println(" :"+hs);

Iterator itr = hs.iterator();

while(itr.hasNext())
{
System.out.println(itr.next());
}

//ListIterator not available for Set

Enumeration enm=Collections.enumeration(hs);

for(;enm.hasMoreElements();)
{
	System.out.println(enm.nextElement());
}

}

}

output:
:[to, test, string, random1, some]
to
test
string
random1
some
to
test
string
random1
some

You may also like to read:
Can a Collection be concurrent
HashSet using Generic class
How many loops are there in Java