[英]Remove an Object from an arraylist in a hashmap
I need your help, I created this two classes我需要你的帮助,我创建了这两个类
public class Arch <N,T>{
T label;
N start;
N end;
...constructor...
public class Graph <N,T>{
private ArrayList<N> nodes;
private HashMap<N,ArrayList<T>> arch; //for each Node I have saved an arrayList of Archs
//connected to him
private int nNode;
private int nArch;
private boolean oriented;
...constructor..
I need a method in Graph to delete an Arch from the ArrayList that I have in the hashmap.我需要 Graph 中的一种方法来从 hashmap 中的 ArrayList 中删除 Arch。
I tried like this in the class Graph:我在 class 图表中这样尝试:
public void deleteArch(N start, N end){
ArrayList<Arch<N,T>> archsForNode=(ArrayList<Arch<N,T>>)arch.get(start);
for(Arch<N,T> a : archsForNode){
if(a.start==start || a.end == end) {
archsForNode.remove(a);
}
}
}
but when I tested it in my test main the result is that nothing changed in my ArrayList in the hashmap.但是当我在我的测试主体中对其进行测试时,结果是 hashmap 中的 ArrayList 没有任何变化。
someone can help me please!请有人可以帮助我!
thank you all谢谢你们
I am 90% certain that your problem's root cause is that your classes are not overriding Object#equals(Object)
and Object#hashCode()
methods.我 90% 确定您的问题的根本原因是您的类没有覆盖
Object#equals(Object)
和Object#hashCode()
方法。 In order for a remove()
function to work, it needs to compare the object being passed to the function against members of the collection you are iterating over so that the object that's equal to the argument is removed. In order for a
remove()
function to work, it needs to compare the object being passed to the function against members of the collection you are iterating over so that the object that's equal to the argument is removed.
I suggest you research overriding these methods for proper implementation.我建议您研究覆盖这些方法以正确实施。 But, in summary, your classes must implement these methods and in the case of complex classes (classes containing other object references) each one of these classes must override these methods.
但是,总而言之,您的类必须实现这些方法,并且在复杂类(包含其他 object 引用的类)的情况下,这些类中的每一个都必须覆盖这些方法。 The reason why classes like
String
work in these cases is because the String
class overrides these methods.像
String
这样的类在这些情况下起作用的原因是String
class 覆盖了这些方法。 For your custom classes, you must do the same.对于您的自定义类,您必须这样做。 Think about this logically.
从逻辑上思考这个问题。 How could a collection magically remove and object if there is no way for the code to decide which objects are equal to what you are looking for?
如果代码无法确定哪些对象与您要查找的对象相等,那么集合如何神奇地删除和 object?
I suspect deleteArch
throws a ConcurrentModificationException
because you are modifying archsForNode
while iterating over it:我怀疑
deleteArch
会抛出ConcurrentModificationException
,因为您在迭代它时正在修改archsForNode
:
for(Arch<N,T> a : archsForNode){
if(a.start==start || a.end == end) {
archsForNode.remove(a);
}
}
This is not allowed.这是不允许的。
For more information see this Q&A.有关更多信息,请参阅此问答。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.