一组 是在Java中的接口,用于指定具有收藏合同独特的元素。如果object1.equals(object2)返回true,则Object1和object2中只有一个在Set实现中具有位置。
片段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]
在下面的代码片段中,我们必须实现HashSet ,其中的元素既不按插入顺序存储也不按排序顺序存储。
片段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]
我n个下面的代码片段中,我们必须实现TreeSet中 的哪些元素存储在排序顺序。
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]