要设置的数组不会截断 java 数组
Array to Set not cuts off java array
我正在将数组列表转换为 java 中的集合,但生成的集合没有产生预期的结果。
String[] characterName = {"C","A","P","T","A","I","N","A","M","E","R","I","C","A"};
String[] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
List<String> pool = new ArrayList<String>();
for(int i=0;i<characterName.length;i++) {
pool.add(characterName[i]);
}
int difference = 19-characterName.length;
for(int i=0;i<difference;i++) {
pool.add(alphabet[i]);
}
Collections.shuffle(pool);
Set<String> poolSet= new HashSet<>();
poolSet.addAll(pool);
我已经对此进行了调试,但是当我将池中的所有内容添加到哈希集时,它只会添加数组的前 11 个字符。尽管当我调试时,它说 pool = 19,但它只加 11。我说错了吗?看起来很简单,但并不是全部相加。非常感谢任何输入。
java 中的 Set
要么包含项目,要么不包含。它们不包含它的多个副本。
在您的示例中,CAPTAINAMERICAABCDE
中只有 11 个唯一字符 CAPTINMERBD
。这就是为什么你最后得到 11 的原因。
您可能希望使用 List
,因为这样可以允许同一事物的多个实例。
我正在将数组列表转换为 java 中的集合,但生成的集合没有产生预期的结果。
String[] characterName = {"C","A","P","T","A","I","N","A","M","E","R","I","C","A"};
String[] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
List<String> pool = new ArrayList<String>();
for(int i=0;i<characterName.length;i++) {
pool.add(characterName[i]);
}
int difference = 19-characterName.length;
for(int i=0;i<difference;i++) {
pool.add(alphabet[i]);
}
Collections.shuffle(pool);
Set<String> poolSet= new HashSet<>();
poolSet.addAll(pool);
我已经对此进行了调试,但是当我将池中的所有内容添加到哈希集时,它只会添加数组的前 11 个字符。尽管当我调试时,它说 pool = 19,但它只加 11。我说错了吗?看起来很简单,但并不是全部相加。非常感谢任何输入。
Set
要么包含项目,要么不包含。它们不包含它的多个副本。
在您的示例中,CAPTAINAMERICAABCDE
中只有 11 个唯一字符 CAPTINMERBD
。这就是为什么你最后得到 11 的原因。
您可能希望使用 List
,因为这样可以允许同一事物的多个实例。