Reputation: 125
I have 2 lists with different types of names of citys:
ArrayList<City> list1 = new ArrayList<City>();
ArrayList<City> list2 = new ArrayList<City>();
list1.add(Birmingham);
list1.add(Amsterdam);
list1.add(Rotterdam);
list1.add(Brussels);
list2.add(Brussels);
list2.add(Brussels);
list2.add(Rotterdam);
list2.add(Amsterdam);
list2.add(Amsterdam);
if i compare these 2 lists, it should be true
if i have a third list:
list3.add(brussELtss);
list3.add(Rotterdam);
list3.add(Amsterdam);
If i compare the third list to either of the first 2 it should be false
I tried comparing, equals and containsall, but that doesnt work.
Upvotes: 0
Views: 340
Reputation: 34424
You have set for this, Have a look at Hashset implementation which will containing the unique element. Your object City needs to implement Comparable/Comparator to decide on equality. Add first element in set and then start adding second list, if add method returns true then element is already there
Update :- After reading comment, i can think of below O(n) time complexity Algo
Iterate over first list and construct a map(HashMap as implemetaion) with element as key and count as value
Iterate over second list, if element does not exist in map they are not equal.
If element found, reduce the count by one for that element in map
At last iterate over map, if there is an element with count other than zero, then list are not equal
Upvotes: 1