Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare every item to every other item in ArrayList

Tags:

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     while(itr.hasNext()){         // 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.

like image 744
JavaKungFu Avatar asked Feb 14 '11 15:02

JavaKungFu


People also ask

How do you compare two elements in an ArrayList?

The ArrayList. equals() is the method used for comparing two Array List. It compares the Array lists as, both Array lists should have the same size, and all corresponding pairs of elements in the two Array lists are equal. Parameters: This function has a single parameter which is an object to be compared for equality.

How do you check if all items in a list are in another list Java?

The containsAll() method of List interface in Java is used to check if this List contains all of the elements in the specified Collection. So basically it is used to check if a List contains a set of elements or not.

Can you use for each in ArrayList?

The forEach() method of ArrayList used to perform the certain operation for each element in ArrayList. This method traverses each element of the Iterable of ArrayList until all elements have been Processed by the method or an exception is raised.


1 Answers

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)   } } 
like image 162
Kaleb Brasee Avatar answered Nov 25 '22 15:11

Kaleb Brasee