2014-11-01 143 views
0

所以我有2個txt文件,都具有IP列表:在它的端口刪除相關領域

我加載列表到自己的linkedlists

public static LinkedList<DataValue> result = new LinkedList<DataValue>(); 
    public static LinkedList<DataValue> badresult = new LinkedList<DataValue>(); 

他們有一個類值

public static class DataValue { 
    protected final String first; 
    protected final int second; 

    public DataValue(String first, int second) { 
     this.first = first; 
     this.second = second; 
    } 
} 

試圖所以這樣做是爲了使... 負荷LIST1到結果 加載列表2到badresult

那麼所有badresult從結果

除去,以便裝載完成

public static void loadList() throws IOException { 
    BufferedReader br = new BufferedReader(new FileReader("./proxy.txt")); 
     String line; 
     String args[]; 
     String first;int second; 
     while ((line = br.readLine()) != null) { 
      args = line.split(":"); 
      first = args[0]; 
      second = Integer.parseInt(args[1]); 
      result.add(new DataValue(first, second)); 
     } 
} 
public static void loadUsed() throws IOException { 
    BufferedReader br = new BufferedReader(new FileReader("./usedproxy.txt")); 
     String line; 
     String args[]; 
     String first;int second; 
     while ((line = br.readLine()) != null) { 
      args = line.split(":"); 
      first = args[0]; 
      second = Integer.parseInt(args[1]); 
      badresult.add(new DataValue(first, second)); 
     } 
} 

,這裏是我在試圖刪除的結果都是一樣的結果鏈表

public static void runCleaner() { 
    for (DataValue badresultz : badresult) { 
     if (result.remove(badresultz)) { 
      System.out.println("removed!"); 
     } else { 
      System.out.println("not removed..."); 
     } 
    } 
} 
+0

在'DataValue'中實現'equals'方法 – 2014-11-01 20:55:23

回答

1

在Java中失敗的嘗試我們使用equals方法檢查對象是否相等。你的DataValue類沒有實現這個,所以當你要求從列表中刪除一個對象時,它實際上是使用==(由Object類實現的)比較對象。

System.out.println((new DataValue("hello", 1)).equals(new DataValue("hello", 1))); 
// prints false 

這是因爲2個對象實際上是由2個不同的空間在內存中表示的。要解決此問題,您需要覆蓋DataValue類中的equals方法,同樣優先考慮hashCode方法也是很好的做法。我使用eclipse爲我生成了2種方法:

@Override 
public int hashCode() { 
    final int prime = 31; 
    int result = 1; 
    result = prime * result + ((first == null) ? 0 : first.hashCode()); 
    result = prime * result + second; 
    return result; 
} 

@Override 
public boolean equals(Object obj) { 
    if (this == obj) 
     return true; 
    if (obj == null) 
     return false; 
    if (getClass() != obj.getClass()) 
     return false; 
    DataValue other = (DataValue) obj; 
    if (first == null) { 
     if (other.first != null) 
      return false; 
    } else if (!first.equals(other.first)) 
     return false; 
    if (second != other.second) 
     return false; 
    return true; 
} 
+0

工作得很好謝謝:) – Travs 2014-11-01 21:23:02