Check if a value exists in ArrayList

后端 未结 7 2550
长发绾君心
长发绾君心 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条回答
  •  余生分开走
    2020-11-27 13:49

    Please refer to my answer on this post.

    There is no need to iterate over the List just overwrite the equals method.

    Use equals instead of ==

    @Override
    public boolean equals (Object object) {
        boolean result = false;
        if (object == null || object.getClass() != getClass()) {
            result = false;
        } else {
            EmployeeModel employee = (EmployeeModel) object;
            if (this.name.equals(employee.getName()) && this.designation.equals(employee.getDesignation())   && this.age == employee.getAge()) {
                result = true;
            }
        }
        return result;
    }
    

    Call it like this:

    public static void main(String args[]) {
    
        EmployeeModel first = new EmployeeModel("Sameer", "Developer", 25);
        EmployeeModel second = new EmployeeModel("Jon", "Manager", 30);
        EmployeeModel third = new EmployeeModel("Priyanka", "Tester", 24);
    
        List employeeList = new ArrayList();
        employeeList.add(first);
        employeeList.add(second);
        employeeList.add(third);
    
        EmployeeModel checkUserOne = new EmployeeModel("Sameer", "Developer", 25);
        System.out.println("Check checkUserOne is in list or not");
        System.out.println("Is checkUserOne Preasent = ? " + employeeList.contains(checkUserOne));
    
        EmployeeModel checkUserTwo = new EmployeeModel("Tim", "Tester", 24);
        System.out.println("Check checkUserTwo is in list or not");
        System.out.println("Is checkUserTwo Preasent = ? " + employeeList.contains(checkUserTwo));
    
    }
    

提交回复
热议问题