如何将唯一的值放入数组? [英] How do I put only unique values into an array?
问题描述
node_marked_array.add(strings[0]);
for (int i = 0; i < strings.length; i++) {
for (int a = 0; a < strings2.length; a = a + 2) {
if (node_marked_array.get(i).equals(strings2[a])) {
if (!node_marked_array.get(i).equals(strings2[a + 1])) {
// System.out.println("marked node: " + node_marked_array.get(i) + "=" + strings2[a] + ", added node " + strings2[a+1]);
node_marked_array.add(strings2[a + 1]);
}
}
}
}
有一个数组名为 strings2
的元素分别是:
I have an array named strings2
of elements each being:
1,2,1,3,2,3,2,4,3,2,5,5,2,
,我的代码应该通过数组,如果它匹配,例如数组中名为的元素的任何元素
: {1,2,3,4,5}
与 strings2
的每个偶数元素。它检查上面的数组的 i + 1
元素,以查看元素是否已经添加到标记的数组中,如果不是则添加它。然而,即使在
and my code is supposed to go through the array and if it matches for example any of the element that is in the array called strings
: {1,2,3,4,5}
with that of strings2
for each even element. It checks the i+1
element of the array above to see if the element is already added to the marked array, if it isn't then it adds it. However I am seeing duplicate values even with
if (!node_marked_array.get(i).equals(strings2[a + 1]))
输出:
1 2 3 3 4 2 5 2 5 5
推荐答案
Use Set
. Array is the wrong data type for this problem.
它包含一个 .toArray()
方法,将返回一个数组 之后,您构建了该集合,如果这是您需要的。
It contains a .toArray()
method that will give you back an array after you've constructed the set, if that is what you require.
这篇关于如何将唯一的值放入数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!