在 Java 中将 HashSet 中的元素转换为数组
java 8object oriented programmingprogramming更新于 2024/10/21 15:50:00
首先,创建一个 HashSet 并将元素添加到其中 −
HashSet hs = new HashSet(); // 将元素添加到哈希集中 hs.add("B"); hs.add("A"); hs.add("D"); hs.add("E"); hs.add("C"); hs.add("F"); hs.add("K");
现在让我们将上面的 HashSet 转换为数组 −
Object[] ob = hs.toArray();
以下是将 HashSet 中的元素转换为数组的示例 −
示例
import java.util.*; public class Demo { public static void main(String args[]) { // create a hash set HashSet hs = new HashSet(); // 将元素添加到哈希集中 hs.add("B"); hs.add("A"); hs.add("D"); hs.add("E"); hs.add("C"); hs.add("F"); hs.add("K"); hs.add("M"); hs.add("N"); System.out.println("Elements in the set: "+hs); Object[] ob = hs.toArray(); System.out.println("Converting elements to array..."); for (int i = 0; i < ob.length; i++) { System.out.println(ob[i]); } } }
输出
Elements in the set: [A, B, C, D, E, F, K, M, N] Converting elements to array... A B C D E F K M N