zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Java Set.toArray()方法:用Set集合中的所有对象创建一个数组

2023-06-13 09:12:00 时间
Java 集合类中的 Set.toArray() 方法可以用 Set 集合中的所有对象创建一个数组。

根据 Set 集合的大小,生成相同长度的数组,该数组包含了 Set 集合中的所有内容。

toArray()

把 Set 集合中的所有内容保存到一个新的数组中。


public static void main(String[] args){

 Set set = new HashSet(); //定义Set集合对象

 set.add( apple //向集合中添加对象

 set.add( computer 

 set.add( book 

 set.add(new Date());

 Object[] toArray = set.toArray(); //获取集合的数组形式

 System.out.println( 数组的长度是: +toArray.length); //输出数组长度

}

运行结果为:
数组的长度是:4

使用指定的数组存储 Set 集合中的所有内容。

toArray(T[] a)

参数说明:


注意:对于返回值,如果参数指定的数组能够容纳 Set 集合的所有内容,就使用该数组保存 Set 集合中的所有对象,并返回该数组;否则,返回一个新的能够容纳 Set 集合中所有内容的数组。

如果参数指定的数组长度大于 Set 集合的大小,那么数组的剩余空间全部复制为 null 值。

本示例把 Set 集合的所有内容输出到超出 Set 集合大小的数组中。超出 Set 集合的部分内容使用 null 代替。代码如下:


public static void main(String[] args){

 Set set = new HashSet(); //定义Set集合

 set.add( apple //向集合中添加对象

 set.add( computer 

 set.add( book 

 set.add( String也是对象,不是基本数据类型 

 String[] strArray = new String[6]; //定义长度为6的字符串数组

 String[] toArray = (String[])set.toArray(strArray); //将集合转换为字符串数组形式

 System.out.println( 数组的长度是: +toArray.length); //输出数组长度

 for(String string:toArray){ //循环遍历字符串数组

 System.out.println(string); //输出字符串数组内容

}

运行结果如下:
数组的长度是:6
computer
String也是对象,不是基本数据类型
apple
book
null

22661.html

java