Check if a value exists in ArrayList

后端 未结 7 2594
长发绾君心
长发绾君心 2020-11-27 13:37

How can I check if a value that is written in scanner exists in an ArrayList?

List lista = new ArrayList

        
7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 14:00

    Just use ArrayList.contains(desiredElement). For example, if you're looking for the conta1 account from your example, you could use something like:

    if (lista.contains(conta1)) {
        System.out.println("Account found");
    } else {
        System.out.println("Account not found");
    }
    

    Edit: Note that in order for this to work, you will need to properly override the equals() and hashCode() methods. If you are using Eclipse IDE, then you can have these methods generated by first opening the source file for your CurrentAccount object and the selecting Source > Generate hashCode() and equals()...

提交回复
热议问题