【发布时间】:2020-12-17 18:06:26
【问题描述】:
所以我有一个未定义的对象,我想将它从一个数组列表中删除,而另一个未定义的对象具有相同的值,这样我就可以拥有一个可以处理我扔给它的每个对象的类,而不必创建每种对象类型都有不同的方法。
问题是,即使对象的内容相同,因为它是另一个实例,整体价值是不同的。
喜欢:
Msg.TradeMsg@1d97b82
Msg.TradeMsg@1a3337fb\
即使这 2 个对象具有相同的值,但它们是不同的,并且不会通过 .equals 返回 true
所以我的问题是,如何从数组列表中删除一个对象,当它具有相同的字段但我不知道 Object 类是什么时?
或者有没有更简单的方法?
代码:
//valueToDelete can be of any type like User, Items, Trade...
public void deleteFromJson(Object valueToDelete, String fileLocation) throws IOException {
Gson gson = new Gson();
ArrayList<Object> oldValues = new ArrayList<>();
//If valueTiDelete is null, the whole content of the file will be deleted
if (valueToDelete != null) {
//Get Content out of array and add it to the ArrayList
for (Object oldValue : updateOldValues(fileLocation)) {
oldValues.add(gson.fromJson(oldValue.toString(), valueToDelete.getClass()));
}
//This does not work, because the objects are 2 different instances but still have all the same fields.
//How can I remove an object from the array list, when it has the same fields but I don't know what the Object class is?
oldValues.remove(valueToDelete);
}
// Write updated content in file
Writer writer = new FileWriter(fileLocation);
gson.toJson(oldValues, writer);
writer.flush();
writer.close();
}
【问题讨论】:
-
您在问题中一针见血:
.equals()不会返回 true。您需要重写.equals()方法,以便它检测到您喜欢的等效对象。一旦您编写了equals()方法,大多数 IDE 还会为您生成hashCode()方法。