如何将唯一的值到一个数组? [英] How do I put only unique values into an array?

查看:154
本文介绍了如何将唯一的值到一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  node_marked_array.add(串[0]);的for(int i = 0; I< strings.length;我++){
    为(int类型的= 0;一个与所述; strings2.length; A = A + 2){
        如果(node_marked_array.get(ⅰ).equals(strings2 [α])){
            如果(!node_marked_array.get(ⅰ).equals(strings2 [A + 1])){
                //的System.out.println(标记的节点:+ node_marked_array.get(I)+=+ strings2 [α] +,添加的节点+ strings2 [A + 1]);
                node_marked_array.add(strings2 [A + 1]);
            }
        }
    }
}

我有一个名为数组 strings2 元素的每一个都:


  

1,2,1,3,2,3,2,4,3,2,5,5,2,


和我的code应该去通过阵列,以及是否是示例匹配任何一个名为字符串数组中的元素: {1,2,3,4,5} strings2 的每个元素,甚至。它检查来看到上面的阵列I + 1 元素如果元素已经被添加到标记阵列,如果它不那么它增加了它。但是我看到重复的值甚至

 如果(!node_marked_array.get(I).equals(strings2 [A + 1]))


  

输出: 1 2 3 3 4 2 5 2 5 5



解决方案

使用 设置 。 Array为这个问题的错误的数据类型。

它包含一个<一个href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Set.html#toArray%28%29\"><$c$c>.toArray()方法会给你回一个数组的您已经构建了一套,如果这是你所需要的。

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]);
            }
        }
    }
}

I have an array named strings2 of elements each being:

1, 2, 1, 3, 2, 3, 2, 4, 3, 2, 5, 5, 2,

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]))

output: 1 2 3 3 4 2 5 2 5 5

解决方案

Use Set. Array is the wrong data type for this problem.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆