2013-04-29 104 views
1

我想检查两个arraylist,然后插入到另一个arrayList。但是当我这样做时,我会得到重复的值。如何解决此问题并删除重复项。 我会得到中位数,并检查中位数是大于还是小于然后在第三个数组列表中插入数值。ArrayList打印复制代码

public static void cluster() { 
    Kmeans kk = new Kmeans(); 
    for (int x = 0; x < cluster1.size() && cluster1 != null; x++) { 
    for (int y = 0; y < cluster2.size() && cluster2 != null; y++) { 
     String s1 = cluster1.get(x); 
     String s2 = cluster2.get(y); 
     try { 
     int median = kk.distance(s1, s2); 
     if (s1.length() > median) { 
      kmcluster1.add(s1); 
      kmcluster2.add(s2); 
     } 
     } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
     } 
    } 
    } 
} 
public static int median(String q, String w) { 
    int h = q.length(); 
    int h1 = w.length(); 
    int kk = 0; 
    if (h > h1) { 
    kk = h - h1; 
    return kk; 
    } else kk = h1 - h; 
    return kk; 
} 
+0

请格式化您的代码。 – 2013-04-29 16:27:04

+0

你能在我的代码中发现错误吗? – newuser 2013-04-29 16:33:27

回答

1

有在你的代码中的错误:

x < cluster1.size() && cluster1 != null; // will not prevent a null pointer exception 

您应该使用

cluster1 != null && x < cluster1.size(); 

或最好做一个空检查只是一次进入循环前。

而且,是的回答你的问题使用HashSet而不是ArrayList。它会安静地忽略重复的添加(不会抛出异常)。实例化集群如下:

Set<String> kmcluster1 = new HashSet<String>(); 
Set<String> kmcluster2 = new HashSet<String>(); 

使用HashSet,而不是ArrayListLinkedHashSet,而不是LinkedList只要你不想让你的数据结构包含任何重复。

2

ArrayList s允许按设计重复值。如果您想要一个禁止重复的数据结构,请考虑使用Set的实例。

+0

你能给我一个这样的代码吗 – newuser 2013-04-29 16:31:45

+0

你还没有在这里提供足够的代码,但我假设'kmcluster1'和'kmcluster2'是你在原始问题中引用的'ArrayList'实例。如果你希望这些数据结构忽略重复值,它们应该被声明为某种'Set' - 一个'HashSet'或'TreeSet'可以工作。如果您不能将这些集合重新声明为不同的类型,那么只需在添加之前检查集合中是否已存在该值(使用'.contains(...)'方法)。 – matt 2013-04-29 16:40:57