将 Java 中的 HashSet 中的元素转换为数组
首先,创建一个 HashSet 并向其中添加元素 −
HashSet hs = new HashSet();
// add elements to the hash set
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();
// add elements to the hash set
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP