java –cp

Java Set is a collection of elements (Or objects) that contains no duplicate elements. Java Set is an interface that extends Collection interface. Unlike List, Java Set is NOT an ordered collection, it’s elements does NOT have a particular order. Java Set does NOT provide a control over the position where you can insert an element. You cannot access elements by their index and also search elements in the list.

Java Set是元素(或对象)的集合,其中不包含重复的元素。 Java Set是扩展Collection接口的接口。 与List不同,Java Set不是有序集合,它的元素没有特定的顺序。 Java的集提供对在那里你可以插入一个元素的位置的控制。 您不能按元素索引访问元素,也不能在列表中搜索元素。

Java集 (Java Set)

In this section, we will discuss some of the important points about Java Set:

在本节中,我们将讨论有关Java Set的一些重要点:

  • Java Set interface is a member of the Java Collections Framework.Java Set接口是Java Collections Framework的成员。
  • Unlike List, Set DOES NOT allow you to add duplicate elements.不同于列表中,设置不允许添加重复的元素。
  • Set allows you to add at most one null element only.Set允许您最多仅添加一个null元素。
  • Set interface got one default method in Java 8: spliterator.Set接口在Java 8中有一个默认方法:spliterator。
  • Unlike List and arrays, Set does NOT support indexes or positions of it’s elements.与List和数组不同,Set不支持其元素的索引或位置。
  • Set supports Generics and we should use it whenever possible. Using Generics with Set will avoid ClassCastException at runtime.集支持泛型,我们应该尽可能使用它。 与Set一起使用泛型将避免在运行时出现ClassCastException。
  • We can use Set interface implementations to maintain unique elements.我们可以使用Set接口实现来维护唯一元素。

Java Set类图 (Java Set Class Diagram)

Java Set interface extends Collection interface. Collection interface extends Iterable interface. Some of the frequently used Set implementation classes are HashSet, LinkedHashSet, TreeSet, CopyOnWriteArraySet and ConcurrentSkipListSet. AbstractSet provides a skeletal implementation of the Set interface to reduce the effort in implementing Set.

Java Set接口扩展了Collection接口。 Collection接口扩展了Iterable接口。 一些常用的Set实现类是HashSet,LinkedHashSet,TreeSet,CopyOnWriteArraySet和ConcurrentSkipListSet。 AbstractSet提供Set接口的基本实现,以减少实现Set的工作量。

Java Set方法 (Java Set Methods)

In this section we will discuss some of the useful Java Set methods:

在本节中,我们将讨论一些有用的Java Set方法:

  1. int size(): to get the number of elements in the Set.int size():获取Set中元素的数量。
  2. boolean isEmpty(): to check if Set is empty or not.boolean isEmpty():检查Set是否为空。
  3. boolean contains(Object o): Returns true if this Set contains the specified element.boolean contains(Object o):如果此Set包含指定的元素,则返回true。
  4. Iterator iterator(): Returns an iterator over the elements in this set. The elements are returned in no particular order.Iterator iterator():返回对此集合中的元素进行迭代的迭代器。 元素以不特定的顺序返回。
  5. Object[] toArray(): Returns an array containing all of the elements in this set. If this set makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.Object [] toArray():返回包含此集合中所有元素的数组。 如果此集合保证其迭代器返回其元素的顺序,则此方法必须以相同的顺序返回元素。
  6. boolean add(E e): Adds the specified element to this set if it is not already present (optional operation).boolean add(E e):如果指定的元素尚不存在,则将其添加到此集合中(可选操作)。
  7. boolean remove(Object o): Removes the specified element from this set if it is present (optional operation).boolean remove(Object o):如果存在,则从此集合中删除指定的元素(可选操作)。
  8. boolean removeAll(Collection c): Removes from this set all of its elements that are contained in the specified collection (optional operation).boolean removeAll(Collection c):从此集合中删除所有包含在指定集合中的元素(可选操作)。
  9. boolean retainAll(Collection c): Retains only the elements in this set that are contained in the specified collection (optional operation).boolean keepAll(Collection c):仅保留此集合中包含在指定集合中的元素(可选操作)。
  10. void clear(): Removes all the elements from the set.void clear():从集合中删除所有元素。
  11. Iterator iterator(): Returns an iterator over the elements in this set.Iterator iterator():返回对此集合中的元素进行迭代的迭代器。

要设置的Java数组 (Java Array to Set)

Unlike List, We cannot convert a Java Set into an array directly as it’s NOT implemented using an Array.
So We cannot use Arrays class to get the view of array as set. We can follow another approach. We can convert an array into List using Arrays.asList() method, then use it to create a Set. By using this approach, we can covert a Java Array to Set in two ways. Let us discuss them one by one using one simple example.

与List不同,我们不能将Java Set直接转换为数组,因为它不是使用Array实现的。
所以我们不能使用Arrays类来获取数组的视图。 我们可以采用另一种方法。 我们可以使用Arrays.asList()方法将数组转换为List,然后使用它创建一个Set。 通过使用这种方法,我们可以通过两种方式隐式设置Java数组。 让我们使用一个简单的示例一个接一个地讨论它们。

Approach-1
In this approach, first We need to create a List using given array and use it to create a Set as shown below.

方法1
在这种方法中,首先我们需要使用给定的数组创建一个List,并使用它来创建Set,如下所示。

import java.util.*;public class ArrayToSet {public static void main(String[] args) {String[] vowels = {"a","e","i","o","u"};Set<String> vowelsSet = new HashSet>(Arrays.asList(vowels));System.out.println(vowelsSet);/*** Unlike List, Set is NOt backed by array, * so we can do structural modification without any issues.*/vowelsSet.remove("e");System.out.println(vowelsSet);vowelsSet.clear();System.out.println(vowelsSet);}
}

Approach-2
In this approach, we do NOT use intermediate List to create a Set from an Array. First create an empty HashSet, then use Collections.addAll() to copy array elements into the given Set as shown below.

方法2
在这种方法中,我们不使用中间List从数组创建Set。 首先创建一个空的HashSet,然后使用Collections.addAll()将数组元素复制到给定的Set中,如下所示。

import java.util.*;public class ArrayToSet2 {public static void main(String[] args) {String[] vowels = {"a","e","i","o","u"};Set<String> vowelsSet = new HashSet<>();Collections.addAll(vowelsSet, vowels); System.out.println(vowelsSet);/** * Unlike List, Set is NOt backed by array, * so we can do structural modification without any issues.*/vowelsSet.remove("e");System.out.println(vowelsSet);vowelsSet.clear();System.out.println(vowelsSet);}
}

Output:-
When we run above two programs, we will get the same output as shown below.

输出:-
当我们在两个程序之上运行时,将获得如下所示的相同输出。

[a, e, u, i, o]
[a, u, i, o]
[]

Java设置为数组 (Java Set to Array)

In this section, we will write a program to convert a Set of Strings into an Array of String using Set.toArray() method as shown below.

在本节中,我们将编写一个程序,使用Set.toArray()方法将一组字符串转换为一组字符串,如下所示。

import java.util.*;public class SetToArray {public static void main(String[] args) {Set<String< vowelsSet = new HashSet<>();// add examplevowelsSet.add("a");vowelsSet.add("e");vowelsSet.add("i");vowelsSet.add("o");vowelsSet.add("u");//convert Set to ArrayString strArray[] = vowelsSet.toArray(new String[vowelsSet.size()]);System.out.println(Arrays.toString(strArray)); }
}

Output:-
When we run above program, we will get the following output as shown below.

输出:-
当我们运行上述程序时,将获得以下输出,如下所示。

[a, e, u, i, o]

Java集合排序 (Java Set Sorting)

As we know, Set (HashSet) does NOT support sorting elements directly. It stores and display it’s elements in random order.

众所周知,Set(HashSet)不直接支持排序元素。 它以随机顺序存储和显示其元素。

However, we have some approaches to sort it’s elements as shown below:

但是,我们有一些方法可以对元素进行排序,如下所示:

import java.util.*;public class SetSortingExample {public static void main(String[] args) {Set<Integer> intsSet = new HashSet<>();Random random = new Random();for (int i = 0; i  {return (o2-o1);});System.out.println("Reverse Sorting: " + intsList2);// Approach-3Set<Integer> sortedSet = new TreeSet<>(intsSet);System.out.println("Sorted Set: " + sortedSet);}
}

Output:-
When we run above program, we will see the following output.

输出:-
当我们运行上面的程序时,我们将看到以下输出。

[560, 864, 176, 657, 135, 103, 40, 123, 555, 589]
Natural Sorting: [40, 103, 123, 135, 176, 555, 560, 589, 657, 864]
Before Sorting: [560, 864, 176, 657, 135, 103, 40, 123, 555, 589]
Reverse Sorting: [864, 657, 589, 560, 555, 176, 135, 123, 103, 40]
Sorted Set: [40, 103, 123, 135, 176, 555, 560, 589, 657, 864]

Java设置通用操作 (Java Set Common Operations)

Most common operations performed on Java Set are add, addAll, clear, size etc. Below is a simple Java Set example showing common method usage.

在Java Set上执行的最常见操作是add,addAll,clear,size等。下面是一个简单的Java Set示例,显示了常用方法的用法。

import java.util.*;public class SetCommonOperations
{public static void main(String args[]) {Set<String> vowels= new HashSet<>();//add examplevowels.add("A");vowels.add("E");vowels.add("I");//We cannot insert elements based on index to a SetSystem.out.println(vowels);Set<String> set = new HashSet<>();set.add("O");set.add("U");//appending set elements to lettersvowels.addAll(set);System.out.println(vowels);//clear example to empty the setset.clear();//size exampleSystem.out.println("letters set size = " + vowels.size());vowels.clear();vowels.add("E"); vowels.add("E");vowels.add("I"); vowels.add("O");System.out.println("Given set contains E element or not? = " + vowels.contains("E"));}
}

Output:-

输出:-

[A, E, I]
[A, E, U, I, O]
letters set size = 5
Given set contains E element or not? = true

Java Set迭代器 (Java Set Iterator)

Below is a simple example showing how to iterate over Java Set.

下面是一个简单的示例,显示了如何遍历Java Set。

import java.util.*;public class SetIteratorExample
{public static void main(String[] args) {Set<Integer> set = new HashSet<>();for(int i=0; i<5; i++) set.add(i);Iterator iterator = set.iterator();//simple iterationwhile(iterator.hasNext()){int i = (int) iterator.next();System.out.print(i + ", ");}System.out.println("\n" + set);//modification of set using iteratoriterator = set.iterator();while(iterator.hasNext()){int x = (int) iterator.next();if(x%2 ==0) iterator.remove();}System.out.println(set);//changing set structure while iteratingiterator = set.iterator();while(iterator.hasNext()){//ConcurrentModificationException hereint x = (int) iterator.next(); if(x==1) set.add(10);}}
}

Java设置为流 (Java Set to Stream)

Below is a simple example showing how to convert a Java Set to Stream and perform some operations as per our requirements.

以下是一个简单的示例,显示了如何将Java Set转换为Stream并按照我们的要求执行一些操作。

import java.util.*;public class SetToStream {public static void main(String[] args) {Set<String> vowelsSet = new HashSet<>();// add examplevowelsSet.add("a");vowelsSet.add("e");vowelsSet.add("i");vowelsSet.add("o");vowelsSet.add("u");//convert set to streamvowelsSet.stream().forEach(System.out::println);}
}

Output:-

输出:-

a
e
u
i
o

Java SE 9集 (Java SE 9 Set)

In Java SE 9 release, Oracle Corp is going to add some useful utility methods to Set interface. It’s better to understand them with some simple and useful examples.

在Java SE 9版本中,Oracle Corp将向Set接口添加一些有用的实用程序方法。 最好通过一些简单而有用的示例来理解它们。

Please go through my tutorial at “Java SE 9: Set Factory Methods” to learn them.

请仔细阅读我在“ Java SE 9:设置工厂方法 ”中的教程以学习它们。

That’s all of a quick roundup on Set in Java. I hope these Java Set examples will help you in getting started with Set collection programming.

这就是Java中Set的快速总结。 我希望这些Java Set示例可以帮助您入门Set集合编程。

Thank you for reading my tutorials. Please drop me a comment if you like my tutorials or have any issues or suggestions or any type errors.

感谢您阅读我的教程。 如果您喜欢我的教程或有任何问题或建议或任何类型错误,请给我评论。

翻译自: https://www.journaldev.com/13242/java-set

java –cp

java –cp_Java设置–用Java设置相关推荐

  1. java swing 文件选择,设置默认文件选择路径,桌面路径

    在上传文件,选择文件的时候,往往会遇到路径选择的问题,比如,一般上传的默认路径是 我的文档,而我们恰好需要默认在桌面,那怎么办呢? 下面的内容也许会帮到你! 首先,看java swing 方面,使用 ...

  2. jar java classpath_win7中java编程工具安装 java环境变量设置

    win7中java编程工具安装 java环境变量设置 Question:编译是显示'javac'不是内部或外部命令,也不是可运行的程序或批处理文件 解决: 在[系统变量]里编辑java_home.cl ...

  3. 【Android NDK 开发】JNI 方法解析 ( C/C++ 设置 Java 对象字段 | 查找字段 | 设置字段 )

    文章目录 I . 设置 Java 对象 属性 流程 II . 查找 Java 对象属性 ( GetFieldID ) III . 设置 Java 对象属性 ( SetXxxField ) I . 设置 ...

  4. 【Java 网络编程】TCP 数据传输示例 ( 客户端参数设置 | 服务器端参数设置 | ByteBuffer 存放读取数据类型 )

    文章目录 I 客户端代码示例 II 服务器端代码示例 III 运行结果 I 客户端代码示例 import java.io.IOException; import java.io.InputStream ...

  5. java环境变量设置与java查看安装路径

    把jdk安装到计算机中之后,我们来进行设置使java环境能够使用. 首先右键点我的电脑.打开属性.然后选择"高级"里面的"环境变量",在新的打开界面中的系统变量 ...

  6. java classpath设置_Java CLASSPATH设置

    Java CLASSPATH设置 CLASSPATH: CLASSPATH是一个环境变量,Application ClassLoader使用它来定位和加载.class文件. CLASSPATH定义路径 ...

  7. eclipse java的jvm匹配_eclipse设置jvm

    Java虚拟机默认分配64M内存,如果你的应用比较大,超出64M内存,Java虚拟机就会抛出outOfMemoryError,并停止运行.不管是什么应用(Web应用.Application等),只需要 ...

  8. java mariadb 使用,java连接mariaDB的设置,java连接mariadb

    java连接mariaDB的设置,java连接mariadb java连接mariaDB数据库的设置:(tomcat 8) 第一种方法:使用tomcat自带的mysql-connector-java- ...

  9. java excel条件格式_Java 设置Excel条件格式(高亮条件值、应用单元格值/公式/数据条等类型)...

    概述 在Excel中,应用条件格式功能可以在很大程度上改进表格的设计和可读性,用户可以指定单个或者多个单元格区域应用一种或者多种条件格式.本篇文章,将通过Java程序示例介绍条件格式的设置方法,设置条 ...

最新文章

  1. linux 硬链接和软链接
  2. mybatis深入理解(一)之 # 与 $ 区别以及 sql 预编译
  3. 腾讯AI Lab涂兆鹏:如何提升神经网络翻译的忠实度 | PhD Talk #22
  4. Flume 1.7 源码分析(二)整体架构
  5. junit4.0/4.9与testng6.4 pom依赖对比
  6. 用一辈子去领悟的生活经典[转帖]
  7. tomcat部署教程
  8. 女生的拳头有多厉害?
  9. Magento教程 8:如何新增首页选单?
  10. 桌面环境选择_Ubuntu 18.04 桌面环境初体验
  11. 固态硬盘—国内视频行业的暂时救星?
  12. 大话设计模式之装饰者模式
  13. 开源的魔兽世界参考架构——mangos--网络游戏引擎BigWorld 服务器介绍
  14. HTML5七夕情人节表白网页制作【一起跨年表白代码】HTML+CSS+JavaScript
  15. 信息安全专业学习规划
  16. 汉得能效中台 || Choerodon猪齿鱼商业版V0.23正式上线!
  17. 在QT界面中使用ico/png等图片文件,生成exe后不依赖外部文件
  18. 计算机网络有什么部分组成,计算机网络有哪些组成部分和详细对比
  19. 【NLP开发】Python实现中文、英文分词
  20. java ppt 绘图,PPT图片别再直接插入,这样处理一下,让你的PPT秒变高逼格

热门文章

  1. UITextField 对比 UITextView
  2. 【转】深入理解JVM—JVM内存模型
  3. daemon进程(转)
  4. ASP.NET配置FCKeditor文本编辑器
  5. [转载] Python-科赫雪花(科克曲线)
  6. [转载] python 1
  7. [转载] [Python图像处理] 二十二.Python图像傅里叶变换原理及实现
  8. 机器学习-数据科学库-day1
  9. C# partial 说明
  10. pytorch---之指定GPU