JavaKungFu JavaKungFu - 1 month ago 56
Java Question

Compare every item to every other item in ArrayList

I'm having trouble with what I thought should be a pretty simple problem.

I need to compare every item in an arrayList with every other item in the the list without comparing items to themselves. It's not as simple as calling an equals() comparison, it involves some custom logic that I've omitted from my code below. Also the ArrayList should not be changed in any way.

The problem I seem to be having is that once I get into the second loop, I don't know if I have another object to compare to (since its a variable sized list).

for(int i =0; i< list.size(); i++){
//get first object to compare to
String a = list.get(i).getA();

Iterator itr = list.listIterator(i + 1 ); // I don't know if i + 1 is valid
// compare A to all remaining items on list

I think I probably going about this the wrong way, I'm open to suggestions or tips on how to do this better.

for (int i = 0; i < list.size(); i++) {
  for (int j = i+1; j < list.size(); j++) {
    // compare list.get(i) and list.get(j)