Home > Java > javaTutorial > body text

How to implement Set interface in JShell in Java 9?

王林
Release: 2023-09-06 19:01:06
forward
753 people have browsed it

在Java 9中如何在JShell中实现Set接口?

JShell 是 Java 9 中的一个命令行工具,用于执行表达式、类、接口、方法等简单语句。

Set是 Java 中的一个接口,它指定具有唯一元素的集合的契约。如果object1.equals(object2)返回true,那么object1和object2中只有一个在Set实现中占有一席之地。

在下面的代码片段中,我们必须使用Set.of()方法。 Set.of()方法返回的集合是不可变的,因此它不支持add()方法。如果我们尝试添加一个元素,则会抛出UnsupportedOperationException。如果我们想创建一个HashSet集合,它支持add()方法来测试Set的唯一属性。它返回 false 表示插入重复的“Adithya”条目失败。

Snippet-1

<strong>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]</strong>
Copy after login

在下面的代码片段中,我们必须实现 HashSet,其中元素既不按插入顺序存储,也不按排序顺序存储。

代码片段-2

<strong>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]</strong>
Copy after login

在下面的代码片段中,我们必须实现 LinkedHashSet ,其中元素存储在插入的顺序。

Snippet-3

<strong>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]</strong>
Copy after login

在下面的代码片段中,我们必须实现 TreeSet,其中元素存储在 <强>排序顺序

Snippet-4

<strong>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]
</strong>
Copy after login

The above is the detailed content of How to implement Set interface in JShell in Java 9?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template