Checking arraylists
I have a function that checks two arraylists to see if they contain the same elements. It works by copying the two lists, and then using the iterator.remove() function to remove matches. If the lists are empty at the end the function returns true. This works out fine, but the problem is that after the function runs, both of the lists are empty and i want them to retain their values. I haven't programmed in java in a while so i have forgotten how to do this. Right now the code is written as such:
List theList = this.getList();
This is just creating a pointer, so that when i remove it it removes from both. Is there a way to actually copy all of the elements easily. So i still retain the list values?
[726 byte] By [
mateobusa] at [2007-10-3 4:55:49]

Yes. ArrayList, for example, provides a constructor that copies an existing Collection.
final List oldList = ...;
final List newList = new ArrayList(oldList);
Regardless, you should address the algorithm you're using to compare two Lists. For example, iterating over each and adding them to a Set looking for the first return value that indicates the element existed would be a trivial way. Another might be to iterate over the first list, invoking contains() on the second list with each element until returning true or hitting the end of the list. Or if you could just make it easy on yourself and try this:
if (firstList.containsAll(secondList)) {
System.out.println("I guess they have the same elements!");
} else {
System.out.println("Apparently they didn't.");
}
Thanks for the help, im clearly a noobieThe reason I have done it this way is because the lists can contain the elements in a different order. However if one list contains more instances than other, it should return false. Does that compare all function do that?
So you're saying each List must have the exact same number of each element but not necessarily in the same order? If that's the case, then logically if the first list contains every element in the second list and they're the same size they must have the same number of each element. Or am I misunderstanding?