Check if one list contains element from the other

前端 未结 12 2634
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 20:45

I have two lists with different objects in them.

List list1;
List list2;

I want to check if element from list

12条回答
  •  猫巷女王i
    2020-11-30 21:24

    According to the JavaDoc for the .contains(Object obj):

    Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

    So if you override your .equals() method for your given object, you should be able to do: if(list1.contains(object2))...

    If the elements will be unique (ie. have different attributes) you could override the .equals() and .hashcode() and store everything in HashSets. This will allow you to check if one contains another element in constant time.

提交回复
热议问题