Most efficient way to see if an ArrayList contains an object in Java

后端 未结 12 1126
孤城傲影
孤城傲影 2020-11-30 18:25

I have an ArrayList of objects in Java. The objects have four fields, two of which I\'d use to consider the object equal to another. I\'m looking for the most efficient wa

12条回答
  •  失恋的感觉
    2020-11-30 18:58

    You could use a Comparator with Java's built-in methods for sorting and binary search. Suppose you have a class like this, where a and b are the fields you want to use for sorting:

    class Thing { String a, b, c, d; }
    

    You would define your Comparator:

    Comparator comparator = new Comparator() {
      public int compare(Thing o1, Thing o2) {
        if (o1.a.equals(o2.a)) {
          return o1.b.compareTo(o2.b);
        }
        return o1.a.compareTo(o2.a);
      }
    };
    

    Then sort your list:

    Collections.sort(list, comparator);
    

    And finally do the binary search:

    int i = Collections.binarySearch(list, thingToFind, comparator);
    

提交回复
热议问题