元素不会从列表中删除

时间:2015-03-13 15:40:49

标签: java list

我是java中的新手并试图从列表数组中删除元素。已经尝试了很多变种,但总是得到输入错误,没有从列表中删除任何内容。尝试过使用像if (list.contains(tch.getSurname())这样的条件,总是得到输入错误的错误。希望,你能帮我解决这个问题。

package com.company;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

    static Main main = new Main();
    /*public static Teachers tch = new Teachers(surname, name);*/
    public static List<Teachers> list = new ArrayList<Teachers>();

    public static void io(){
        Scanner sc = new Scanner(System.in);
        String surname = "";
        String name = "";
        Teachers tch = new Teachers(surname, name);
        for (int i=0; i<2; i++) {
            surname = sc.nextLine();
            name = sc.nextLine();
            tch = new Teachers(surname, name);
            list.add(tch);
        }
        for(Teachers nstr : list) {
            System.out.println(nstr.toString());
        }

        for(Teachers t : list) {
            String input = sc.nextLine();
            if (input == tch.getSurname()) {
                list.remove(input);
            } else {
                System.out.println("Wrong input");
            }

        }

        for(Teachers nstr : list) {
            System.out.println(nstr.toString());
        }
    }

    public static void main(String[] args) {
        main.io();


    }
}

更新: 所以我尝试使用迭代器,我添加了:

for (Iterator<Teachers> it = list.iterator(); it.hasNext();){
            Teachers t = it.next();
            if (t.equals(tch.getSurname())){
                it.remove();
            }
        }

并删除:

for(Teachers t : list) {
            String input = sc.nextLine();
            if (input.equals(tch.getSurname())) {
                list.remove(tch);
            } else {
                System.out.println("Wrong input");
            }
        }

但它也没有帮助我从列表数组中删除元素,它只是复制我的列表输入。

2 个答案:

答案 0 :(得分:1)

您的错误是if(input == tch.getSurname()。这比较确切的参考,看它是否相同。而是使用if(input.equals(tch.getSurname()))检查内容。 同时将该循环中的引用从tch更改为t。您没有使用列表中的当前元素,而是使用您创建的元素添加到列表中。最后将list.remove(input)更改为list.remove(t)。这样就可以删除实际元素,而不仅仅是尝试删除姓氏字符串。

将for循环更改为

Iterator<Teachers> i = list.iterator();
while(i.hasNext()){
     Teachers t = i.next();
      ...
}

然后删除它只需使用i.remove()

答案 1 :(得分:0)

现在循环完美无缺。

for(Teachers t : list) {
                String input = sc.nextLine();
                if (input.equals(t.getSurname())) {
                    list.remove(t);
                } else {
                    System.out.println("Wrong input");
                }
            }