2013-04-29 114 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