【问题标题】:How to check Object ArrayList contain single attribute of Object without Loop如何检查对象 ArrayList 是否包含没有循环的对象的单个属性
【发布时间】:2015-04-14 10:04:30
【问题描述】:

Here is the answer of this question but I need is there any other way

假设 Person 是一个包含属性的类

  • personId
  • 人名
  • 个人地址

一个 ArrayList 包含千人对象,我想检查“11” personId 是否在 ArayList 中?

一种方法是迭代(循环)arraylist并逐个检查。

有没有其他方法可以解决这个问题?

【问题讨论】:

  • 是的,创建第二个Set of personId 来测试或模拟数据库索引,方法是创建一个额外的Map of personIdperson
  • 你可以建立一个HashMap<Integer, Person>,其中整数是Person.personId,然后使用简单的get:get(id) == null
  • 你能给我看一些示例吗,但请记住我使用的是 Java,我只需要使用 ArrayList 而不是 HashMap 或其他一些集合。
  • 如果你只使用一个 ArrayList ,那么无论是隐式地还是显式地,都无法绕过它。你想达到什么目的?
  • 我想检查 11 personId 是否在 arraylist 中的千人对象中?我知道 arraylist 中有 contains() 但这比较整个人对象但只有 presonId 属性。

标签: java arrays list search arraylist


【解决方案1】:

基于persionId 实现equalshashCodejava.util.ArrayList#contains 会给你结果。这个解决方案就像遍历列表并找到对象一样好。

【讨论】:

    【解决方案2】:

    在 POJO 中为 person Id 覆盖 equals() 和 hashcode() 方法

    例如:

    import java.util.ArrayList;
    
    public class Test {
    private int personId;
    private String name;
    //getters and Setters
    
    
    
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + personId;
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
           return true;
        if (obj == null)
           return false;
        if (getClass() != obj.getClass())
           return false;
        Test other = (Test) obj;
        if (personId != other.personId)
           return false;
        return true;
    }
    public static void main(String[] args) {
        ArrayList<Test> test=new ArrayList<Test>();
    
    Test t=new Test();
    t.setName("Sireesh");
    t.setPersonId(1);
    
    Test t1=new Test();
    t1.setName("Ramesh");
    t1.setPersonId(2);
    
    Test t2=new Test();
    t2.setName("Rajesh");
    t2.setPersonId(3);
    
    
    test.add(t);
    test.add(t1);
    test.add(t2);
    
    Test tx=new Test();
    tx.setPersonId(1);
    System.out.println(test.contains(tx));
    //Returns true
    
    }
    }
    

    【讨论】:

    • @YasirShabbirChoudhary 不,如果您只使用Lists,则不会。但是,最好同时覆盖 hashCode()equals() 以满足这些操作约定,否则某些 Java 集合将无法按预期工作,即如果您使用 HashSet 会遇到麻烦。有关更多信息,请参阅此问题stackoverflow.com/questions/2265503/…
    猜你喜欢
    • 2018-03-08
    • 2012-12-04
    • 2012-02-02
    • 1970-01-01
    • 2021-04-27
    • 2016-04-21
    • 2013-04-22
    • 1970-01-01
    • 2023-03-26
    相关资源
    最近更新 更多