-1

I have two arrays of objects: ArrayList<Object> list1 и ArrayList<Object> list2.

Example of my code (simplified):

Class Object1 {
String str1 = "example";
}

Class Object2 {
String str2 = "example";
}

ArrayList<Object> list1 = new ArrayList<>();
list1.add(new Object1());
ArrayList<Object> list2 = new ArrayList<>();
list2.add(new Object2());

Problem: I need to compare fields str1 and str2 (between Object1 and Object2 that location in a different arrays)

Gleb
  • 13
  • 3
  • 1
    let `Object1` and `Object2` implement the same Interface which declares a getter method in which each class returns its string. Then let both classes implement `Comparable` interface in which each class compares its string with the return value of the common interfaces getter method. – Timothy Truckle Oct 17 '16 at 08:37
  • Possible duplicate of [Java Compare Two List's object values?](http://stackoverflow.com/questions/16207718/java-compare-two-lists-object-values) – saurav Oct 17 '16 at 08:39

3 Answers3

0

you can compare list1.get(0).str1 with list2.get(0).str2. In case you are using a for loop, in place of get(0), use get(i).

Animesh Jena
  • 1,541
  • 1
  • 25
  • 44
0

Any reason why you can't iterate through 1 list, call the getter for the field and compare it with the corresponding object in the other list?

for (int i = 0; i < list1.size(); i++) {
    Object obj1 = list1.get(i);
    Object obj2 = list2.get(i);
    System.out.println(obj1.str1.equals(obj2.str2)); // Better use getter here instead
}
Hung Luong
  • 166
  • 1
  • 10
  • In this case, I do not have access to getters. What can be wrong? (This code is used in the method not being "main") – Gleb Oct 17 '16 at 09:34
  • @GlebTserr Technically, nothing. But design-wise, it's bad practice and should be avoided as it breaks encapsulation. – Hung Luong Oct 17 '16 at 09:41
0

You can compare str1 and str2 like

list1.get(indexOfObject1InList1).str1.equals(list2.get(indexOfObject2InList2).str2)
Linh
  • 57,942
  • 23
  • 262
  • 279