gpt4 book ai didi

java - 删除LinkedList中的相关字段

转载 作者:行者123 更新时间:2023-12-01 12:20:34 25 4
gpt4 key购买 nike

所以我有 2 个 txt 文件,其中都有 ip:port 列表

我正在将列表加载到它们自己的链接列表中

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

他们有类(Class)值(value)

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 加载到结果中将 list2 加载到 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...");
}
}
}

最佳答案

在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;
}

关于java - 删除LinkedList中的相关字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26693121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com