I'm very new to java and I have two List<String>
. When I do :
list1.equals(list2)
is giving me false
. Eventhough the list are same.
Is it the right way to check the equality?
I'm very new to java and I have two List<String>
. When I do :
list1.equals(list2)
is giving me false
. Eventhough the list are same.
Is it the right way to check the equality?
You could use isEqualList
from Apache's ListUtils
:
isEqualList
public static boolean isEqualList(java.util.Collection list1,
java.util.Collection list2)
Tests two lists for value-equality as per the equality contract in List.equals(java.lang.Object).
This method is useful for implementing List when you cannot extend AbstractList. The method takes Collection instances to enable other collection types to use the List implementation algorithm.
The relevant text (slightly paraphrased as this is a static method) is:
Compares the two list objects for equality. Returns true if and only if both lists have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.equals(e2)).) In other words, two lists are defined to be equal if they contain the same elements in the same order. This definition ensures that the equals method works properly across different implementations of the List interface. Note: The behaviour of this method is undefined if the lists are modified during the equals comparison.
It is the correct way. Your lists are not equal as you say they are. Try printing them for visual inspection.
For two lists to be equal, they need to have the same order. I can only assume that you want to ignore the ordering of the two lists when considering equality.
For a comparison that ignores order, you can compare two Map<String, Integer>
instances (where the Integer
is the count per string).
eg:
public <T> boolean isEqualIgnoreOrder(List<T> l1, List<T> l2) {
if (l1.size() != l2.size()) {
return false;
}
Map<T, Integer> m1 = createMap(l1);
Map<T, Integer> m2 = createMap(l2);
return m1.equals(m2);
}
protected <T> Map<T, Integer> createMap(List<T> list) {
Map<T, Integer> map = new HashMap<T, Integer>();
for (T item : list) {
Integer prevCount = map.get(item);
map.put(prevCount == null ? 1 : prevCount + 1);
}
return map;
}
This type of collection is known as a bag. More discussion here