This question already has answers here:
Remove object from ArrayList with some Object property [closed]
                                
                                    (4个答案)
                                
                        
                3年前关闭。
            
        

public void addPopulace()
{
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter name");
    String name = sc.next();
    System.out.println("Enter size");
    int size = sc.nextInt();
    System.out.println("Enter X-Coordinate");
    int x = sc.nextInt();
    System.out.println("Enter Y-Coordinate");
    int y = sc.nextInt();
    Populace p = new Populace(name, size, x, y );
    list.add(p);
}

public void removePopulace()
{
    Scanner rmv = new Scanner( System.in );
    System.out.println("Enter populace name to be removed");
    String rmvName = rmv.next();
    Populace p = new Populace(rmvName);
    list.remove(p);
}


第一种方法提示用户输入平民及其所需的特征,并将其添加到数组列表中。如何仅通过以平民的名字提示iser来获得第二种方法来消除平民。民众当前的格式如下:
人口数x y

最佳答案

您需要在equals()类中重写hashcode()Populace,以便在调用list.remove()时将删除该对象。

基本上,您的equals()方法应提供关于两个Populace对象如何相等的逻辑(例如通过它们的namesize)。

public class Populace {

    //add your existing code here

    @Override
    public boolean equals(Object object) {
        //provide logic on how two objects are equal, check name, size, etc..
    }

    @Override
    public int hashCode() {
        //return hashcode
    }

}

10-08 09:22