如何在java中检查是否设置了具有某些字符串值的对象?

2022-09-01 12:51:31

我有一组对象。每个对象都有字符串值。

我需要选择值等于“方向”的所有对象。this

是否可以在不迭代集合的情况下进行迭代?


答案 1

一般来说,不可以。您需要循环访问该集合并检查每个对象,以查看该属性是否等于您正在搜索的值。这是一个操作。O(n)

有一种情况下,您可以在不迭代的情况下执行此操作。如果对象的方法是根据该属性的相等性定义的,并且该方法也已正确实现,则可以使用 hashSet.contains 及时查找具有正确值的对象,而无需循环访问该集。equalsStringhashCodeO(1)

正如我所提到的,这是一个非常具体的用例,而不是一个通用的解决方案。如果字符串是某种唯一标识符,则可能很有用,但它不适用于您的特定用例。

您可能还需要考虑更适合您的用例的其他集合。例如,如果您使用的是番石榴,那么您可以考虑使用多地图

相关


答案 2

是的,这可以通过覆盖 equals() 方法来实现。

@Override 
public boolean  equals (Object object) {

}

您只想检查在 equals 方法中一切正常。

法典:

package com.webapp.test;

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

public class EmployeeModel {    

    public EmployeeModel(String name, String designation, long age) {
        this.name = name;
        this.designation = designation;
        this.age = age;
    }

    private String name;
    private String designation;
    private long age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDesignation() {
        return designation;
    }

    public void setDesignation(String designation) {
        this.designation = designation;
    }

    public long getAge() {
        return age;
    }

    public void setAge(long age) {
        this.age = age;
    }

    @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 == employee.getName() && this.designation == employee.getDesignation() && this.age.equals(employee.getAge())) {
                result = true;
            }
        }
        return result;
    }
}

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<EmployeeModel> employeeList = new ArrayList<EmployeeModel>();
    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 Present = ? " + 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 Present = ? " + employeeList.contains(checkUserTwo));

}

输出:

Check checkUserOne is in list or not 
Is checkUserOne Present = ? true
Check checkUserTwo is in list or not 
Is checkUserTwo Present = ? false