Set:
- Set doesn’t allow duplicates.
- Set is not index based.
HashSet Methods are:
boolean add(E e) | Adds the specified element to this set if it is not already present. |
void clear() | Removes all of the elements from this set. |
Object clone() | Returns a shallow copy: the elements themselves are not cloned. |
boolean contains(Object o) | Returns true if this set contains the specified element. |
boolean isEmpty() | Returns true if this set contains no elements. |
Iterator<E> iterator() | Returns an iterator over the elements in this set. |
boolean remove(Object o) | Removes the specified element from this set if it is present. |
int size() | Returns the number of elements in this set (its cardinality). |
Note: Set is not providing any methods to perform index-based operations.
Implementations are:
- HashSet: It doesn’t maintain insertion order
- LinkedHashSet: It maintains insertion order of elements.
- TreeSet: It maintains sorted order of elements.
Program to store elements into HashSet and display:
import java.util.*; class Code { public static void main(String[] args) { Set<Integer> set = new HashSet<Integer>(); set.add(50); set.add(40); set.add(30); set.add(20); set.add(10); System.out.println(“Set : ” + set); } } Output: Random order of elements |
Program to store elements into LinkedHashSet and display:
import java.util.*; class Code { public static void main(String[] args) { Set<Integer> set = new LinkedHashSet<Integer>(); set.add(50); set.add(40); set.add(30); set.add(20); set.add(10); System.out.println(“Set : ” + set); } } Output: 50, 40, 30, 20, 10 |
Program to store elements into TreeSet and display:
import java.util.*; class Code { public static void main(String[] args) { Set<Integer> set = new TreeSet<Integer>(); set.add(50); set.add(40); set.add(30); set.add(20); set.add(10); System.out.println(“Set : ” + set); } } Output: 10, 20, 30, 40, 50 |
Remove duplicates in ArrayList:
- ArrayList is ordered and allow duplicates.
- To remove duplicates in array, we simply convert into Set and display
import java.util.*; class Code { public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); for(int i=1 ; i<=4 ; i++) { list.add(i+2); list.add(i+3); } System.out.println(“List : ” + list); Set<Integer> set = new HashSet<Integer>(list); System.out.println(“Set : ” + set); } } Output: List : [3, 4, 4, 5, 5, 6, 6, 7] Set : [3, 4, 5, 6, 7] |