What is the different between Set and List

Set and List explanation

  • Set – Stored elements in unordered or shuffles way, and does not allow duplicate values.
  • List – Stored elements in ordered way, and allow duplicate values.

Set and List Example


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SetAndListExample 
{
    public static void main( String[] args )
    {
    	System.out.println("List example .....");
    	List<String> list = new ArrayList<String>();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        list.add("1");
        
        for (String temp : list){
        	System.out.println(temp);
        }
        
        System.out.println("Set example .....");
        Set<String> set = new HashSet<String>();
        set.add("1");
        set.add("2");
        set.add("3");
        set.add("4");
        set.add("1");
        set.add("2");
        set.add("5");
        
        for (String temp : set){
        	System.out.println(temp);
        }        
    }
}

Output


List example .....
1
2
3
4
1
Set example .....
3
2
10
5
4

In Set, the stored values are in unordered way, and the duplicated value will just ignored.

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
4 Comment threads
2 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
6 Comment authors
GauritotaramRrJack123Krish Recent comment authors
newest oldest most voted
totaram
Guest
totaram

Chutia… answerssssssss

Rr
Guest
Rr

Why is the list output not ordered?

Gauri
Guest
Gauri

It is ordered, it is not sorted. There is difference between sorted and ordered. Ordered means in the order in which the values were inserted.

Jack123
Guest
Jack123

Thank you helped a lot.. Guys 10 is just a typo its 1 actually.

Melinda
Guest
Melinda

Where did the “10” in Set come from?

Krish
Guest
Krish

I think Its printing mistake. answer is
Set example …..
3
2
1
5
4