Maison > Java > javaDidacticiel > Comment implémenter l'interface Set dans JShell en Java 9 ?

Comment implémenter l'interface Set dans JShell en Java 9 ?

王林
Libérer: 2023-09-06 19:01:06
avant
861 Les gens l'ont consulté

在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>
Copier après la connexion

在下面的代码片段中,我们必须实现 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>
Copier après la connexion

在下面的代码片段中,我们必须实现 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>
Copier après la connexion

在下面的代码片段中,我们必须实现 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>
Copier après la connexion

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal