How to implement a Set interface in JShell in Java 9?

JavaObject Oriented ProgrammingProgramming

JShell is a command-line tool in Java 9 that has been used to execute simple statements like expressions, classes, interfaces, methods, and etc.

A Set is an interface in Java that specifies a contract for collections having unique elements. If object1.equals(object2) returns true, then only one of object1 and object2 have a place in Set implementation.

In the below code snippet, we have to use the Set.of() method. The collection returned by the Set.of() method is immutable, so it doesn't support the add() method. If we trying to add an element, throws UnsupportedOperationException. If we want to create a HashSet collection instead, which supports the add() method to test a unique property of a Set. It returns false indicates that inserting a duplicate "Adithya" entry has failed.

Snippet-1

jshell> Set<String> set = Set.of("Adithya", "Chaitanya", "Jai");
set ==> [Jai, Adithya, Chaitanya]

jshell> set.add("Adithya");
|   java.lang.UnsupportedOperationException thrown:

jshell> Set<String> hashSet = new HashSet<>(set);
hashSet ==> [Chaitanya, Jai, Adithya]

jshell> hashSet.add("Adithya");
$8 ==> false

jshell> hashSet
hashSet ==> [Chaitanya, Jai, Adithya]


In the below code snippet, we have to implement HashSet in which elements neither stored in the order of insertion nor in sorted order.

Snippet-2

jshell> Set<Integer> numbers = new HashSet<>();
numbers ==> []

jshell> numbers.add(12345);
$11 ==> true

jshell> numbers.add(1234);
$12 ==> true

jshell> numbers.add(123);
$13 ==> true

jshell> numbers.add(12);
$14 ==> true

jshell> numbers
numbers ==> [1234, 12345, 123, 12]


In the below code snippet, we have to implement LinkedHashSet in which elements are stored in the order of insertion.

Snippet-3

jshell> Set<Integer> numbers1 = new LinkedHashSet<>();
numbers1 ==> []

jshell> numbers1.add(12345);
$17 ==> true

jshell> numbers1.add(1234);
$18 ==> true

jshell> numbers1.add(123);
$19 ==> true

jshell> numbers1.add(12);
$20 ==> true

jshell> numbers1
numbers1 ==> [12345, 1234, 123, 12]

jshell> numbers1.add(123456);
$22 ==> true

jshell> numbers1
numbers1 ==> [12345, 1234, 123, 12, 123456]


In the below code snippet, we have to implement TreeSet in which elements are stored in sorted order.

Snippet-4

jshell> Set<Integer> numbers2 = new TreeSet<>();
numbers2 ==> []

jshell> numbers2.add(12345);
$25 ==> true

jshell> numbers2.add(1234);
$26 ==> true

jshell> numbers2.add(123);
$27 ==> true

jshell> numbers2.add(12);
$28 ==> true

jshell> numbers2
numbers2 ==> [12, 123, 1234, 12345]

jshell> numbers2.add(123456);
$30 ==> true

jshell> numbers2
numbers2 ==> [12, 123, 1234, 12345, 123456]
raja
Published on 30-Apr-2020 15:14:59
Advertisements