如何在 Java 中将数组转换为 Set 以及将 Set 转换为数组?
java 8object oriented programmingprogramming
Array 是一个容器,可以容纳固定数量的相同类型的实体。数组的每个实体称为元素,每个元素的位置由一个整数(从 0 开始)值(称为索引)表示。
示例
import java.util.Arrays; public class ArrayExample { public static void main(String args[]) { Number integerArray[] = new Integer[3]; integerArray[0] = 25; integerArray[1] = 32; integerArray[2] = 56; System.out.println(Arrays.toString(integerArray)); } }
输出
[25, 32, 56]
虽然 Set 对象是存储另一个对象的集合(对象),但它不允许重复元素,并且最多允许 null 值。
将数组转换为 Set 对象
java.util 包的 Arrays 类提供了一种称为 asList() 的方法。此方法接受数组作为参数并返回 List 对象。使用此方法将数组转换为 Set。
示例
import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class ArrayToSet { public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array to be created ::"); int size = sc.nextInt(); String [] myArray = new String[size]; for(int i=0; i<myArray.length; i++){ System.out.println("Enter the element "+(i+1)+" (String) :: "); myArray[i]=sc.next(); } Set<String> set = new HashSet<>(Arrays.asList(myArray)); System.out.println("Given array is converted to a Set"); System.out.println("Contents of set ::"+set); } }
输出
Enter the size of the array to be created :: 4 Enter the element 1 (String) :: Ram Enter the element 2 (String) :: Rahim Enter the element 3 (String) :: Robert Enter the element 4 (String) :: Rajeev Given array is converted to a Set Contents of set ::[Robert, Rahim, Rajeev, Ram]
设置为数组
Set 对象提供了一种称为 toArray() 的方法。此方法接受一个空数组作为参数,将当前 Set 转换为数组并放置在给定数组中。使用此方法将 Set 对象转换为数组。
示例
import java.util.HashSet; import java.util.Set; public class SetToArray { public static void main(String args[]){ Set<String> set = new HashSet<String>(); set.add("Apple"); set.add("Orange"); set.add("Banana"); System.out.println("Contents of Set ::"+set); String[] myArray = new String[set.size()]; set.toArray(myArray); for(int i=0; i<myArray.length; i++){ System.out.println("Element at the index "+(i+1)+" is ::"+myArray[i]); } } }
输出
Contents of Set ::[Apple, Orange, Banana] Element at the index 1 is ::Apple Element at the index 2 is ::Orange Element at the index 3 is ::Banana