如何仅从给定字符串的数组列表中删除一个民众

时间:2017-04-13 22:44:42

标签: java arrays loops

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

第一种方法提示用户输入民众及其所需的特征并将其添加到arraylist。如何通过仅仅通过民众的名称提示iser来获得第二种方法来移除民众。民众目前的格式如下:
民众大小x y

3 个答案:

答案 0 :(得分:3)

您需要覆盖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
    }

}

答案 1 :(得分:2)

你可以这样做:

for (Populace p: list)
    if (rmvName.equals(p.getName())) {
        list.remove(p);
        break;
    }

答案 2 :(得分:0)

或者只是:

list.removeIf(p -> p.getName().equals(rmvName));