Java Set. Toarray() method: create an array with all the objects in the set collection
•
Java
Grammar 1
toArray()
Example
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); //输出数组长度 }
Grammar 2
toArray(T[] a)
Typical application
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); //输出字符串数组内容 } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码