In Java Collections, what is the difference between Set and List?
In Java Collections, what is the difference between Set and List?
In Collections, List is an ordered sequence of elements whereas Set is a distinct list of elements which is unordered.
List is an ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
Set is a collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.
........ List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(1); for (Integer i : list){ System.out.println(i); }
Output will be…..
1
2
3
1
Set<Integer> set = new HashSet<Integer>(); set.add(1); set.add(2); set.add(3); set.add(1); set.add(2); set.add(5); for (Integer i : set){ System.out.println(i); }
Output will be …..
3
2
1
5