如何通过在java中使用该对象的唯一ID从对象列表中获取特定对象?

时间:2016-01-07 09:38:21

标签: java collections

我希望特定对象具有所有值,方法是使用对象列表中对象的唯一ID。

我已经尝试了,但是在代码下运行时我得到了索引-1。

List<JobDataDetail> jobList = getJobList();
JobDataDetail object = jobList.get(jobList.indexOf(new JobDataDetail(jobReferenceId)));

来自班级

public class JobDataDetail implements Serializable,Comparable<JobDataDetail> {

    public int jobSequence;
    public String jobReferenceId;
    public String jobAddress;
    public String jobScheduledDate;

    public JobDataDetail() {
        super();
        // TODO Auto-generated constructor stub
    }

    public JobDataDetail(int jobSequence){
        super();
        this.jobSequence = jobSequence ;
    }
    public JobDataDetail(String jobReferenceId){
        super();
        this.jobReferenceId = jobReferenceId;
    }

    public int getJobSequence() {
        return jobSequence;
    }
    public void setJobSequence(int jobSequence) {
        this.jobSequence = jobSequence;
    }
    public String getJobReferenceId() {
        return jobReferenceId;
    }
    public void setJobReferenceId(String jobReferenceId) {
        this.jobReferenceId = jobReferenceId;
    }
    public String getJobAddress() {
        return jobAddress;
    }
    public void setJobAddress(String jobAddress) {
        this.jobAddress = jobAddress;
    }
    public String getJobScheduledDate() {
        return jobScheduledDate;
    }
    public void setJobScheduledDate(String jobScheduledDate) {
        this.jobScheduledDate = jobScheduledDate;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((jobReferenceId == null) ? 0 : jobReferenceId.hashCode());
        result = prime * result + jobSequence;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        JobDataDetail other = (JobDataDetail) obj;
        if (jobReferenceId == null) {
            if (other.jobReferenceId != null)
                return false;
        } else if (!jobReferenceId.equals(other.jobReferenceId))
            return false;
        if (jobSequence != other.jobSequence)
            return false;
        return true;
    }

    @Override
    public int compareTo(JobDataDetail another) {
        return this.getJobReferenceId().compareTo(another.getJobReferenceId());
    }

}

2 个答案:

答案 0 :(得分:0)

我已从equals方法中删除了 jobSequence 条件检查,但它正在运行。

答案 1 :(得分:0)

List.indexOf()使用equals()方法来比较对象。

在您的情况下,您假设具有相同jobReferenceId的两个对象相等但您的equals()方法不能这样说(因为jobSequence测试在方法结束时)。

如果您想通过其中一个属性从列表中获取项目,最简单的方法是在Java 8中使用过滤器表达式:

JobDataDetail job = jobList.stream()
                           .filter(j -> j.getAttribute().equals(someValue))
                           .findFirst();

如果Java 8不是一个选项,我会选择在列表上迭代的经典for循环。