2014-11-01 144 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