What is difference between List and Set

Answer: Below are differences:

SetList
Elements in Set in not orderedElements in list are ordered
Allows no duplicate elementDuplicate elements are allowed
Because of unordered collection user has no control over where the values are insertedThis is ordered collection so user of this interface has control over where in list values are inserted
Element of set couldn’t be accessed by indexElements in the list could be accessed by index

Example of set and list:

package com.javahonk.setTest;

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

public class SetTest {

	public static void main(String[] args) {

	Set<String> set = new HashSet<String>();

	set.add("I");
	set.add("I");
	set.add("am");
	set.add("am");
	set.add("Java");
	set.add("Set");		
	System.out.println("Set example:");
	//Duplicate value won't be added
	for (String string : set) {
		System.out.println(string);
	}

	System.out.println("\nList example:");

	List<String> list = new ArrayList<String>();
	list.add("I");
	list.add("I");
	list.add("am");
	list.add("am");
	list.add("Java");
	list.add("List");
	//Duplicate are allowed
	for (String string : list) {
		System.out.println(string);
	}
	}

}

 

Output:

What is difference between List and Set

Leave a Reply

Your email address will not be published. Required fields are marked *