Set
Set Interface-
Java Set is a collection of elements (Or objects) that contains no duplicate elements. Java Set is an interface that extends Collection interface. Set allows you to add at most one null element only.
1. Hash Set:
- HashSet doesn’t allow duplicate entries.
- HashSet allows null as a value.
- HashSet doesn’t guarantee the insertion order of elements.
- HashSet is not thread-safe.Java ArrayList is almost similar to Vector except that it’s unsynchronized, so performance is better in single threaded environment.
package com.csi.collectionconcept;
import java.util.HashSet;
import java.util.Iterator;
public class HashSetConcept {
public static void main(String[] args) {
HashSet hs = new HashSet<>();
hs.add("IT");
hs.add("COMP");
hs.add("MECHANICAL");
hs.add("CIVIL");
hs.add("PRODUCTION");
hs.add("CHEMICAL");
hs.add("PETROLIUM");
hs.add("IT");
hs.add("ELECTRONICS");
Iterator itr = hs.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
Output: COMP CIVIL PETROLIUM IT ELECTRONICS MECHANICAL PRODUCTION CHEMICAL |
2. Tree Set:
- TreeSet doesn’t allow duplicate entries.
- TreeSet does not allow null.
- TreeSet maintains sorting order.
- TreeSet is not thread-safe.
package com.csi.collectionconcept;
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetConcept {
public static void main(String[] args) {
TreeSet ts = new TreeSet<>();
ts.add("IT"); ts.add("COMP");
ts.add("MECHANICAL");
ts.add("CIVIL");
ts.add("PRODUCTION");
ts.add("CHEMICAL");
ts.add("PETROLIUM");
ts.add("IT");
ts.add("ELECTRONICS");
Iterator itr = ts.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
Output: CHEMICAL CIVIL COMP ELECTRONICS IT MECHANICAL PETROLIUM PRODUCTION |