English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The List and Set interfaces both belong to the Collection framework. Both interfaces extend the Collection interface. They are both used to store object collections as a single unit.
In JDK1.2Before that, we used Arrays, Vectors, and Hashtable to group objects into a single unit.
number | key | list | group |
---|---|---|---|
1each | positional access | The list provides positional access to the elements in the collection. | The set does not provide access to the position of elements in the collection |
2 | implementation | The implementations of List are ArrayList, LinkedList, Vector, Stack | The implementation of the set interface is HashSet and LinkedHashSet |
3 | duplicates | We can store duplicate elements in the list. | We cannot store duplicate elements in the set |
4 | reservation | The list maintains the insertion order of elements in the collection | The set does not maintain any order |
5 | empty elements | The list can store multiple null elements | A set can only store one empty element |
import java.util.List; import java.util.ArrayList; import java.util.LinkedList; public class ListExample { public static void main(String[] args) { List<String> al = new ArrayList<String>(); al.add("BMW"); al.add("Audi"); al.add("BMW"); System.out.println("List Elements: "); System.out.print(al); } }
Output Result
List Elements: [BMW, Audi, BMW]
import java.util.Set; import java.util.HashSet; import java.util.TreeSet; public class SetExample { public static void main(String args[]) { int count[] = {2, 4, 3, 5}; Set<Integer> hset = new HashSet<Integer>(); try{ for(int i = 0; i<4; i++{ hset.add(count[i]); } System.out.println(hset); } catch(Exception e){ e.printStackTrace(); } } }
Output Result
[2, 4, 3, 5]