Set cares about uniqueness. It doesn’t allow duplications. Here “equals ( )” method is used to determine whether two objects are identical or not.
Example:
public class Fruit {
public static void main(String[] args) {
HashSet < String > names = new HashSet <= String > ();
names.add(“banana”);
names.add(“cherry”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“banana”);
System.out.println(names);
}
}
Output:
[banana, cherry, kiwi, apple]
Doesn’t follow any insertion order. Duplicates are not allowed.
Example:
public class Fruit {
public static void main(String[] args) {
LinkedHashSet < String > names = new LinkedHashSet < String > ();
names.add(“banana”);
names.add(“cherry”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“banana”);
System.out.println(names);
}
}
Output:
[banana, cherry, apple, kiwi]
Maintains the insertion order in which they have been added to the Set. Duplicates are not allowed.
Example:
public class Fruits {
public static void main(String[] args) {
TreeSet < String > names = new TreeSet < String > ();
names.add(“cherry”);
names.add(“banana”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“cherry”);
System.out.println(names);
}
}
Output:
[apple, banana, cherry, kiwi]
TreeSet sorts the elements in ascending order. And duplicates are not allowed.
We covered nearly 50 + primary Java interview questions in this tutorial for fresh and experienced candidates. Q.1- What is… Read More