Re: How to compare two ArrayList of string?
"John" <rds1226@sh163.net> wrote in message
news:f1ohb4$6oml$1@netnews.upenn.edu...
| If I have two ArrayList of String of the same number of elements, can I do
| comparison?
|
| I want them to be equal as long as they contain the same elements. I don't
| care the order of the elements.
|
| Is the statement possible: if (arraylist1==arraylist2) ......
The == operator returns true only if both variables refer to the same
list--it does not attempt to determine if two distinct list have equivalent
contents. .equals () won't do you any good here either. If the lists have
the same length and you can remove all the items of the second list from the
first, they're equal. If there will never be identical elements in any list,
you can do something like:
Set s1 = new HashSet (arraylist1);
for (Object o : arraylist2) {
if (! s1.contains (o)) // Sets are definately not equal
s1.remove(o);
}
If there can be identical elements, you'll have to count them or otherwise
account for multiples
Map <Object,Integer> m = new HashMap <Object,Integer> ();
for (Object o : arraylist1) {
Integer countInt = m.get(o);
if (countInt == null) {
m.put (o, new Integer (1));
} else {
m.put (o, new Integer (1 + countInt.intValue()));
}
And then subtract the arraylist2 items int he same way. If any item can't
be subtracted, they're not equal.
Or, sort both lists (if the values can be ordered)
Collections.sort(arraylist1);
Collections.sort(arraylist2);
And compare each position. Any unequal item means the lists are not equal.
Cheers,
Matt Humphrey matth@ivizNOSPAM.com http://www.iviz.com/