使用同一对象的另一个实例从 ArrayList<?> 中删除对象
Delete Object out of ArrayList<?> with another instance of the same object
所以我有一个未定义的对象,我想用另一个具有相同值的未定义对象从数组列表中删除它,这样我就可以有一个 class 可以处理我抛给它的每个对象,并且不必为每个对象类型创建不同的方法。
问题是,即使对象的内容相同,因为它是另一个实例,所以整体值不同。
喜欢:
Msg.TradeMsg@1d97b82
Msg.TradeMsg@1a3337fb\
尽管这 2 个对象具有相同的值,但它们是不同的并且不会 return 与 .equals
相同
所以我的问题是,当对象具有相同的字段但我不知道对象 class 是什么时,如何从数组列表中删除对象?
或者有更简单的方法吗?
代码:
//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();
}
要验证两个未知且变化 类 的对象在它们包含的值方面是否相等,您可以
- 覆盖所有可能进入该列表的 类 中的
Object::equals
和 Object::hashCode
,或者
- 使用reflection探测对象内部并深入检查是否相等
第二个比较难做,不仔细的话容易出错。
例如,Hibernate 这样做是为了完成其 脏检查 功能,所以我不会说这是一种不好的做法,但肯定会在灰色区域徘徊。
旁注:有这样的需求通常表明需要重新设计模型
所以我有一个未定义的对象,我想用另一个具有相同值的未定义对象从数组列表中删除它,这样我就可以有一个 class 可以处理我抛给它的每个对象,并且不必为每个对象类型创建不同的方法。
问题是,即使对象的内容相同,因为它是另一个实例,所以整体值不同。
喜欢:
Msg.TradeMsg@1d97b82
Msg.TradeMsg@1a3337fb\
尽管这 2 个对象具有相同的值,但它们是不同的并且不会 return 与 .equals
相同所以我的问题是,当对象具有相同的字段但我不知道对象 class 是什么时,如何从数组列表中删除对象?
或者有更简单的方法吗?
代码:
//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();
}
要验证两个未知且变化 类 的对象在它们包含的值方面是否相等,您可以
- 覆盖所有可能进入该列表的 类 中的
Object::equals
和Object::hashCode
,或者 - 使用reflection探测对象内部并深入检查是否相等
第二个比较难做,不仔细的话容易出错。 例如,Hibernate 这样做是为了完成其 脏检查 功能,所以我不会说这是一种不好的做法,但肯定会在灰色区域徘徊。
旁注:有这样的需求通常表明需要重新设计模型