Code for finding similar rows in two-dimensional arrays - java

I´m trying to find similar rows in multiple two-dimensional arrays as it was described in my previous post. For the below-given example, the answer is false, true, although it should be false, false.
Another very important question is how to adjust this code to arrays with the different number of rows.
I appreciate very much any help. Thanks.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
ArrayList<Integer[]> array1 = new ArrayList<Integer[]>();
ArrayList<Integer[]> array2 = new ArrayList<Integer[]>();
ArrayList<Integer[]> array3 = new ArrayList<Integer[]>();
array1.add(new Integer[]{1,2,3}); array1.add(new Integer[]{1,0,3});
array2.add(new Integer[]{1,0,3}); array2.add(new Integer[]{0,0,3});
array3.add(new Integer[]{1,2,3}); array3.add(new Integer[]{0,3,3});
for (int i=0; i<array1.size(); i++) {
boolean answ = equalRows(array1.get(i),array2.get(i),array3.get(i));
System.out.println(answ);
}
}
static class Row extends Object {
private int value;
public Row(int val) {
this.value = val;
}
#Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if((obj == null) || (obj.getClass() != this.getClass()))
return false;
// object must be Row at this point
Row row = (Row)obj;
return (value == row.value);
}
#Override
public int hashCode () {
return this.value;
}
}
private static Map<Row, Integer> map(Integer[] row) {
Map<Row, Integer> rowMap = new HashMap<Row, Integer>();
for (int i=0; i<row.length; i++)
rowMap.put(new Row(row[i]), i);
return rowMap;
}
private static boolean equalRows(Integer[] row1, Integer[] row2, Integer[] row3){
Map<Row, Integer> map1 = map(row1);
Map<Row, Integer> map2 = map(row2);
for (int i=0; i<row3.length; i++){
Row row = new Row(row3[i]);
Integer result1 = map1.get(row);
Integer result2 = map2.get(row);
if (result1 == null || result2 == null) {
return false;
}
}
return true;
}
}
Edit#1
In the first test I´m comparing {1,2,3}, {1,0,3} and {1,2,3}. In the second: {1,0,3}, {0,0,3}, {0,3,3}. The problem with the second row is that {0,0,3} and {0,3,3} are tackled as {0,3}. I don´t know how to modify the code to deferentiate between {0,0,3} and {0,3,3} (I still should use HashMap).
Edit#2
The idea is that first I take rows from array1 and array2 and I put them into maps. Then I take a row from array3 and try to find it in maps. If I can´t find it in any of these maps, then it means that rows are not similar.

To compare two arrays, ignoring nulls you can have
public static <T> boolean equalsExceptForNulls(T[] ts1, T[] ts2) {
if (ts1.length != ts2.length) return false;
for(int i = 0; i < ts1.length; i++) {
T t1 = ts1[i], t2 = ts2[i];
if (t1 != null && t2 != null && !t1.equals(t2))
return false;
}
return true;
}
public static <T> boolean equalsExceptForNulls3(T[] ts1, T[] ts2, T[] ts3) {
return equalsExceptForNulls(ts1, ts2) &&
equalsExceptForNulls(ts1, ts3) &&
equalsExceptForNulls(ts2, ts3);
}
// or generically
public static <T> boolean equalsExceptForNulls(T[]... tss) {
for(int i = 0; i < tss.length - 1; i++)
for(int j = i + 1; i < tss.length; j++)
if(!equalsExceptForNulls(tss[i], tss[j])
return false;
return true;
}
The problem you have is that array3 is being used to determine which rows to compare.
In the first test you are comparing rows 1,2,3 and the second test you are comparing rows 0 and 3. The first test should be false and the second should be true.
I found the issue by stepping through your code in a debugger. I suggest you do the same.
I would also use int[] instead of Integer[]

I'm not quite sure what you are trying to accomplish but could it be that your problem lies in the method
public boolean equals(Object obj) {
if(this == obj)
return true;
if((obj == null) || (obj.getClass() != this.getClass()))
return false;
// object must be Row at this point
Row row = (Row)obj;
return (value == row.value);
}
because with
if(this == obj)
for example you want to have an value comparison - But what you get using the "==" comperator is a comparison of two objects references ?
So maybe
if(this.equals(obj))
is what you want ?
Furthermore, have you tried to step through your code in debugging mode statement per statement ? I guess doiing so could locate your fault quickly ...
cheers :)

There is a basic problem with your approach which leads to this bug. You are using a map to determine the position of an element in the other rows. When constructing the map if there are duplicate elements in the rows, their previous indices will be overwitten. This is exactly what is happening in your case. There is a duplcate zero in the second row of second array.
here is what the maps look like for the second row
map1 = ((Row(1), 0), (Row(0), 1), (Row(3), 3))
map2 = ((Row(0), 1), (Row(3), 3))
Nnotice there are only two elements in map2 bcoz the first one was overwitten with the second one. When you do a lookup with the elements of the second row from the third array the lookup always succeeds (because it it looks only for a 0 and a 3 and never for a 1)
Moreover the condition you check for failure is incomplete i.e
if (result1 == null || result2 == null) {
return false;
}
should be
if (result1 == null || result2 == null || !result1.equals(i) || !result2.equals(i)) {
return false;
}
In my opinion you shouldn't be using a map at all. Instead compare each element one by one. To generalize the code for arrays of different lengths try using size() method of the ArrayList class.
If is important to you that a map should be used, then you should use the index of each array element as the key and the Row object as the value instead of doing the reverse.

Related

Remove duplicate in ArrayList of Custom objects

i'm trying to remove duplicate objects from my array.
I have my custom which is made of two double : x and y.
What i want to do is to remove duplicate ( (x && y) == (x1 && y1)) and if x == x1 i want to keep the object which has the higher y.
ArrayList<MyObject> list = [x(0),y(0)], [x(0),y(0)], [x(0.5),y(0.5], [x(0.5),y(0.6)], [x(1),y(1)];
ArrayList<MyObject> results = [x(0),y(0)], [x(0.5),y(0.6)], [x(1),y(1)];
I tried to implement the equals method but i do not how to use it :
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof MyObject)) {
return false;
}
return (this.x == ((MyObject)obj).x);
}
list is always ordered using Collections.sort by x.
Thanks for all.
Given MyObject like this:
class MyObject {
private final double x;
private final double y;
public MyObject(double x, double y) {
this.x = x;
this.y = y;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyObject myObject = (MyObject) o;
if (Double.compare(myObject.x, x) != 0) return false;
if (Double.compare(myObject.y, y) != 0) return false;
return true;
}
#Override
public int hashCode() {
int result;
long temp;
temp = Double.doubleToLongBits(x);
result = (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(y);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
}
You can implement a unique method that returns a list with unique elements only:
private List<MyObject> unique(List<MyObject> list) {
List<MyObject> uniqueList = new ArrayList<>();
Set<MyObject> uniqueSet = new HashSet<>();
for (MyObject obj : list) {
if (uniqueSet.add(obj)) {
uniqueList.add(obj);
}
}
return uniqueList;
}
And a unit test for it to verify it works:
#Test
public void removeDups() {
List<MyObject> list = Arrays.asList(new MyObject(0, 0), new MyObject(0, 0), new MyObject(0.5, 0.5), new MyObject(0.5, 0.6), new MyObject(1, 1));
List<MyObject> results = Arrays.asList(new MyObject(0, 0), new MyObject(0.5, 0.5), new MyObject(0.5, 0.6), new MyObject(1, 1));
assertEquals(results, unique(list));
}
Note: it's important to implement both equals and hashCode for this to work,
because of the use of a hash map. But you should always do this anyway in your custom classes: provide appropriate equals and hashCode implementations. Btw, I didn't write those equals and hashCode methods. I let my IDE (IntelliJ) generate them automatically from the fields x and y of the class.
Make sure to override equals() method in your custom Object(MyObject).
Then add them into a Set. Now you have unique result set.
Use a Set instead of a List ...
You have to override equals() and hashCode(). The most IDE can generate that for you!
To "convert" a List to a Set you can simply use this:
ArrayList<MyObject> list = ...
Set<MyObject> mySet = new HashSet<MyObject>(list);
Then you have a set with unique elements. You can iterate over the set like this:
for (MyObject o : mySet){
o.getX();
}
The most optimal solution would be if you could use a Set. However, there are two Set implementations in Java: HashSet and TreeSet. HashSet requires that you declare equals and hashCode methods, while TreeSet requires your class to implement Comparable with a compareTo method or supply a Comparator. Neither solution will work in your case because you want to keep the higher y when x is equal. If you sort/calculate equality based on x, y you will have duplicate x, and if you sort/calculate equality based on x only you will get the first x entered, which is not what you want.
Therefore, what we need to do is:
Sort by x ascending, y descending
Convert to Set that preserves original order, but bases equality only on x
Convert back to list (if necessary)
XAscYdesc Comparator Method (Not accounting for nulls):
public int compare(MyObject left, MyObject right) {
int c = left.x - right.x;
if(c != 0) {
return c;
}
return right.y - left.y;
}
XAsc Comparator Method (Not accounting for nulls):
public int compare(MyObject left, MyObject right) {
return left.x - right.x;
}
(Using the Guava library; it's very useful for one-liners like this):
Collections.sort(list, new XAscYdesc());
Lists.newArrayList(ImmutableSortedSet.copyOf(new XAsc(), list));
You need to order your collection on both x and y with x first (think about it as x and y forming an hypothetical number with x on the left side of the decimal point, and y on the right side: when you sort number in growing order, if the integral parts are equal, you sort on the decimal part).
Now, with an equal predicate, it will be difficult to sort values (you can only tell if they are equal, not if one is before another). Instead, you need to implement the comparable interface, with the following method:
public int compare(Object obj) {
if (obj == null || !(obj instanceof MyObject)) {
// raise an Exception
}
MyObject other = (MyObject)obj;
if (x < other.x) return -1;
if (this.x > other.x) return 1;
if (this.y < other.y) return -1;
if (this.y > other.y) return 1;
return 0;
}
If your array is sorted according to this comparison, you just need to keep the last entry with the same x in your array to get what you want. This means that you remove entries unless its successor has a different x.
This method is interesting of you don't want to keep your original data, but only keep the result: it will update the existing array in place, for a complexity of O(n) in time (not counting the sorting, which should happen anyway if I understand your question correctly).
Alternatively, the whole filtering can be achieved by applying a fold on your collection, where folding here is simply keeping the highest y for a same x (as you stated it precisely in your question). Because your collection is already sorted on x, it means that it is naturally partitioned on values of x, so you can build a new collection by accumulating the correct x for each partition in another array. For each element of the array, you compare it with the last inserted entry in your new array, if the x are the same, you replace it with the object with the highest y. If the x are different, you add it to the new array.
The advantage of this approach is that you don't need to change the sorting algorithm, but on the other hand you need a new array. This algorithm should therefore work in O(n) space and time.
Finally, this algorithm may be adapted to an in place update of the original array. It is slightly more complicated, but would let you avoid the extra allocation (crucial on embedded systems).
Pseudo code:
int idx = 0;
while (idx + 1 < Objarray.size()){
MyObj oi = Objarray.get(idx), on = Objarray.get(idx+1);
if (oi.x == on.x) {
if (on.y < oi.y)
Objarray.remove(idx++);
else
Objarray.remove(idx+1);
} else
idx++;
}
Note that while working in constant space, it might be slightly less efficient than the allocating algorithm, because of the way ArrayList works internally (though it should be better than using other usual container types).
/**
*
*/
package test1;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* #author raviteja
*
*/
public class UinquecutomObjects {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Employee e1=new Employee();
e1.setName("abc");
e1.setNo(1);
Employee e2=new Employee();
e2.setName("def");
e2.setNo(2);
Employee e3=new Employee();
e3.setName("abc");
e3.setNo(1);
List<Employee> empList=new ArrayList<Employee>();
empList.add(e1);
empList.add(e2);
empList.add(e3);
System.out.println("list size is "+empList.size());
Set<Employee> set=new HashSet<Employee>(empList);
System.out.println("set size is "+set.size());
System.out.println("set elements are "+set);
}
}
class Employee{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
private int no;
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + no;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (no != other.no)
return false;
return true;
}
}

Compare one ArrayList and combine common elements

I've been working on an algorithm to loop through one ArrayList containing a custom object. I'm now on hour 20 and I've gotten almost nowhere.
ArrayList<TicketItem> all = new ArrayList<>();
// ... 'all' gets filled here ... //
ArrayList<TicketItem> allCopy = new ArrayList<>(all);
for (int i = allCopy.size() - 1; i > 0; i--) {
TicketItem last = allCopy.get(i);
for (int j = 0; j < all.size(); j++) {
TicketItem compare = all.get(j);
if (last.getInt(TicketItem.TICKET_ITEM_ID) != compare.getInt(TicketItem.TICKET_ITEM_ID)) {
if (last.canBeGrouped(compare)) {
last.put(TicketItem.TICKET_ITEM_NUMBER, compare.getInteger(TicketItem.TICKET_ITEM_NUMBER));
allCopy.set(i, last);
break;
}
}
}
}
This works when it wants to and to be honest, it's probably really ugly. I just can't get my head around a better option.
The important method inside TicketItem is this one:
public boolean canBeGrouped(TicketItem other) {
if (other == null)
return false;
if (getBoolean(TicketItem.TICKET_ITEM_VOID))
return false;
if (other.getBoolean(TicketItem.TICKET_ITEM_VOID))
return false;
if (getInteger(TicketItem.MENU_ITEM) == null)
return false;
if (getInteger(TicketItem.MENU_ITEM).equals(other.getInteger(TicketItem.MENU_ITEM))
&& getBigDecimal(TicketItem.TICKET_ITEM_TOTAL).compareTo(
other.getBigDecimal(TicketItem.TICKET_ITEM_TOTAL)) == 0) {
ArrayList<TicketItemModifier> mThis = getModifiers();
ArrayList<TicketItemModifier> mOther = other.getModifiers();
if (mThis == null && mOther == null)
return true;
if (mThis != null && mOther != null) {
if (mThis.size() == mOther.size()) {
for (int i = 0; i < mThis.size(); i++) {
TicketItemModifier m1 = mThis.get(i);
TicketItemModifier m2 = mOther.get(i);
Integer m1MenuModifierId = m1.getInteger(TicketItemModifier.MENU_MODIFIER_ID);
Integer m2MenuModifierId = m2.getInteger(TicketItemModifier.MENU_MODIFIER_ID);
if (!(m1MenuModifierId != null && m2MenuModifierId != null && m1MenuModifierId
.equals(m2MenuModifierId))) {
return false;
}
}
return true;
}
}
}
return false;
}
Again, super ugly especially the for loop in there that works when it wants to. If need be I can modify hashCode and equals methods for both classes TicketItem and TicketItemModifier, however I would like to stay away from those two methods and do something along the lines of Comparable classes because just because they can be grouped does not mean they are equal.
What I want to do basically is go through one ArrayList filled with TicketItem objects and when two can be grouped I need to change the TicketItem object to match it.
I would suggest you create a new property or function like TickeItemCode which should be string concatenation of MENU_ITEM+ "-"+ TICKET_ITEM_TOTAL+ "-" + MENU_MODIFIER_IDs in modifiers list. you can filter the list to remove items where TICKET_ITEM_VOID is true and then sort by new property TickeItemCode and do grouping. This way you can reduce your time from n^2 to nlogn

Check if all values in a map are equal

I need to check if all values in a map are equal. I have a method to perform this task but would like to use a library or native methods. Limitations: Java 5 + Apache Commons libraries.
public static boolean isUnique(Map<Dboid,?> aMap){
boolean isUnique = true;
Object currValue = null;
int iteration = 0;
Iterator<?> it = aMap.entrySet().iterator();
while(it.hasNext() && isUnique){
iteration++;
Object value = it.next();
if(iteration > 1){
if (value != null && currValue == null ||
value == null && currValue != null ||
value != null && currValue != null & !value.equals(currValue)) {
isUnique = false;
}
}
currValue = value;
}
return isUnique;
}
What about this something like this:
Set<String> values = new HashSet<String>(aMap.values());
boolean isUnique = values.size() == 1;
how about
return (new HashSet(aMap.values()).size() == 1)
I know the original questions asks for solutions in Java 5, but in case someone else searching for an answer to this question is not limited to Java 5 here is a Java 8 approach.
return aMap.values().stream().distinct().limit(2).count() < 2
You could store the values in a Bidirectional Map and always have this property.
public static boolean isUnique(Map<Dboid,?> aMap) {
Set<Object> values = new HashSet<Object>();
for (Map.Entry<Dboid,?> entry : aMap.entrySet()) {
if (!values.isEmpty() && values.add(entry.getValue())) {
return false;
}
}
return true;
}
This solution has the advantage to offer a memory-saving short cut if there are many differences in the map. For the special case of an empty Map you might choose false as return value, change it appropriately for your purpose.
Or even better without a Set (if your Map does not contain null-values):
public static boolean isUnique(Map<Dboid,?> aMap) {
Object value = null;
for (Object entry : aMap.values()) {
if (value == null) {
value = entry;
} else if (!value.equals(entry)) {
return false;
}
}
return true;
}
As my comment above:
//think in a more proper name isAllValuesAreUnique for example
public static boolean isUnique(Map<Dboid,?> aMap){
if(aMap == null)
return true; // or throw IlegalArgumentException()
Collection<?> c = aMap.getValues();
return new HashSet<>(c).size() <= 1;
}

checking whether two sequences have the same values in the same order (beginning java)

I want to add a method to a class I made that checks whether the two sequences have the same values in the same order.
Here is what I have so far:
public class Sequence {
private int[] values;
public Sequence(int size) { values = new int[size]; }
public void set(int i, int n) { values[i] = n; }
}
public boolean equals (Sequence other)
...??
The first part of the class I think is correct but I'm having a lot of trouble with the method that tests if the values are in the same order. Ideas and feedback would be much appreciated :)
If you want to say wether 2 Sequences are equals, you can override equals method and hashCode to follow contract.
Example using Eclipse tool:
public class Sequence {
private int[] values;
public Sequence(int size) { values = new int[size]; }
public void set(int i, int n) { values[i] = n; }
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(values);
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Sequence other = (Sequence) obj;
if (!Arrays.equals(values, other.values))
return false;
return true;
}
}
Then in a main class you can do the following thing
public static void main(String args[]){
Sequence s = new Sequence(5);
Sequence s2 = new Sequence(5);// new Sequence(4)
s.set(0, 1);
s2.set(0, 1);
System.out.println(s.equals(s2));//will print true
}
You have to take care that if you use my comment code (new Sequence(4)) this will return false and perhaps is not what you want! Then you will have to implement your own equals and not autogenerated by ide.
Arrays have a built in .equals() method: .equals(int[], int[])
Very simple, but hope this helps.
public boolean equals (Sequence other) {
// if sizez are different, automatic false
if (this.getValues().length != other.getValues().length)
return false;
else
int[] array1 = other.getValues();
int[] array2 = this.getValues();
// if any indices are not equal, return false
for (int i = 0; i < other.getValues().length; i++){
if (array1[i] != array2[i])
return false;
}
// it not returned false, return true
return true;
}
First and foremost, you will need to make your .equals() method a member of your Sequence class. Otherwise, you will only have access to one Sequence object.
If you want to check if 2 arrays have the same elements in the same order, all you need to do is compare each element in turn. Is the first element of this one the same as the first element of the other, etc. When you come across a pair of elements that are different, you will be able to return false. Otherwise, you can return true when you have checked each pair of elements.
One issue you may encounter is arrays of different size. Depending on what you're trying to do, you may want to either return false immediately without checking the elements or stop when you reach the end of the shorter array. Based off your question, you probably want the former, but that depends on what problem you are trying to solve.
Your .equals() method will be able to access the values arrays of both this and other even if they aren't public. This is because .equals() as a function of the Sequence class is allowed to access all the members of Sequence, even in Sequence objects other than this.
With this information, you should be able to write your .equals() method.
public boolean equals (Sequence other){
int[] first = this.getValues();
int[] second = other.getValues();
boolean same = true;
if(first.length != second.length){
return false;
}
for(int i = 0; i < first.length; i++){
if(first[i] != second[i]){
return false;
}
}
return same;
}
Note: you will have to make the values array public in the Sequence class or add a getter method to the Sequence class...a getter would be the better option

Self-containing array deep equals

I need to perform structural comparison on two Object[] arrays which may contain themselves:
Object[] o1 = new Object[] { "A", null };
o1[1] = o1;
Object[] o2 = new Object[] { "A", null };
o2[1] = o2;
Arrays.deepEquals(o1, o2); // undefined behavior
Unfortunately, the deepEquals doesn't work in this case. The example above should yield true.
Is there an algorithm which can reliably calculate this?
My idea is roughly as follows:
List<Object> xs = new ArrayList<>();
List<Object> ys = new ArrayList<>();
boolean equal(Object[] o1, Object[] o2, List<Object> xs, List<Object> ys) {
xs.add(o1);
ys.add(o2);
boolean result = true;
for (int i = 0; i < o1.length; i++) {
if (o1[i] instanceof Object[]) {
int idx1 = xs.lastIndexOf(o1[i]);
if (idx1 >= 0) { idx1 = xs.size() - idx1 - 1; }
if (o2[i] instanceof Object[]) {
int idx2 = xs.lastIndexOf(o2[i]);
if (idx2 >= 0) { idx2 = ys.size() - idx2 - 1; }
if (idx1 == idx2) {
if (idx1 >= 0) {
continue;
}
if (!equal(o1[i], o2[i], xs, ys)) {
result = false;
break;
}
}
}
}
}
xs.removeLast();
ys.removeLast();
return result;
}
As I mentioned in my comments above, your code has some compile errors, and you've left out a lot of it, which makes it hard to be 100% sure of exactly how it's supposed to work once the code is completed. But after finishing the code, fixing one clear typo (you wrote idx2 = xs.lastIndexOf(o2[i]), but I'm sure you meant idx2 = ys.lastIndexOf(o2[i])) and one thing that I think is a typo (I don't think that you meant for if (!equal(o1[i], o2[i], xs, ys)) to be nested inside if (idx1 == idx2)), removing some no-op code, and restructuring a bit (to a style that I find clearer; YMMV), I get this:
boolean equal(final Object[] o1, final Object[] o2)
{
return _equal(o1, o2, new ArrayList<Object>(), new ArrayList<Object>());
}
private static boolean _equal(final Object[] o1, final Object[] o2,
final List<Object> xs, final List<Object> ys)
{
if(o1.length != o2.length)
return false;
xs.add(o1);
ys.add(o2);
try
{
for(int i = 0; i < o1.length; i++)
{
if(o1[i] == null && o2[i] == null)
continue;
if(o1[i] == null || o2[i] == null)
return false;
if(o1[i].equals(o2[i]))
continue;
if(! (o1[i] instanceof Object[]) || ! (o2[i] instanceof Object[]))
return false;
final int idx1 = xs.lastIndexOf(o1[i]);
if(idx1 >= 0 && idx1 == ys.lastIndexOf(o2[i]))
continue;
if(! _equal((Object[])o1[i], (Object[])o2[i], xs, ys))
return false;
}
return true;
}
finally
{
xs.remove(xs.size() - 1);
ys.remove(ys.size() - 1);
}
}
which mostly works. The logic is, whenever it gets two Object[]s, it checks to see if if it's currently comparing each of them higher up in the stack and, if so, it checks to see if the topmost stack-frame that's comparing one of them is also the topmost stack-frame that's comparing the other. (That is the logic you intended, right?)
The only serious bug I can see is in this sort of situation:
// a one-element array that directly contains itself:
final Object[] a = { null }; a[0] = a;
// a one-element array that contains itself via another one-element array:
final Object[][] b = { { null } }; b[0][0] = b;
// should return true (right?); instead, overflows the stack:
equal(a, b, new ArrayList<Object>(), new ArrayList<Object>());
You see, in the above, the last element of xs will always be a, but the last element of ys will alternate between b and b[0]. In each recursive call, xs.lastIndexOf(a) will always be the greatest index of xs, while ys.lastIndexOf(b) or ys.lastIndexOf(b[0]) (whichever one is needed) will always be one less than the greatest index of ys.
The problem is, the logic shouldn't be, "the topmost comparison of o1[i] is in the same stack-frame as the topmost comparison of o2[i]"; rather, it should be, "there exists some stack-frame — any stack-frame at all — that is comparing o1[i] to o2[i]". But for efficiency, we can actually use the logic "there is, or has ever been, a stack-frame that is/was comparing o1[i] to o2[i]"; and we can use a Set of pairs of arrays rather than two Lists of arrays. To that end, I wrote this:
private static boolean equal(final Object[] a1, final Object[] a2)
{
return _equal(a1, a2, new HashSet<ArrayPair>());
}
private static boolean _equal
(final Object[] a1, final Object[] a2, final Set<ArrayPair> pairs)
{
if(a1 == a2)
return true;
if(a1.length != a2.length)
return false;
if(! pairs.add(new ArrayPair(a1, a2)))
{
// If we're here, then pairs already contained {a1,a2}. This means
// either that we've previously compared a1 and a2 and found them to
// be equal (in which case we obviously want to return true), or
// that we're currently comparing them somewhere higher in the
// stack and haven't *yet* found them to be unequal (in which case
// we still want to return true: if it turns out that they're
// unequal because of some later difference we haven't reached yet,
// that's fine, because the comparison higher in the stack will
// still find that).
return true;
}
for(int i = 0; i < a1.length; ++i)
{
if(a1[i] == a2[i])
continue;
if(a1[i] == null || a2[i] == null)
return false;
if(a1[i].equals(a2[i]))
continue;
if(! (a1[i] instanceof Object[]) || ! (a2[i] instanceof Object[]))
return false;
if(! _equal((Object[]) a1[i], (Object[]) a2[i], pairs))
return false;
}
return true;
}
private static final class ArrayPair
{
private final Object[] a1;
private final Object[] a2;
public ArrayPair(final Object[] a1, final Object[] a2)
{
if(a1 == null || a2 == null)
throw new NullPointerException();
this.a1 = a1;
this.a2 = a2;
}
#Override
public boolean equals(final Object that)
{
if(that instanceof ArrayPair)
if(a1 == ((ArrayPair)that).a1)
return a2 == ((ArrayPair)that).a2;
else
if(a1 == ((ArrayPair)that).a2)
return a2 == ((ArrayPair)that).a1;
else
return false;
else
return false;
}
#Override
public int hashCode()
{ return a1.hashCode() + a2.hashCode(); }
}
It should be clear that the above cannot result in infinite recursion, because if the program has a finite number of arrays, then it has a finite number of pairs of arrays, and only one stack-frame at a time can be comparing a given pair of arrays (since, once a pair begins to be getting compared, it's added to pairs, and any future attempt to compare that pair will immediately return true), which means that the total stack depth is finite at any given time. (Of course, if the number of arrays is huge, then the above can still overflow the stack; the recursion is bounded, but so is the maximum stack size. I'd recommend, actually, that the for-loop be split into two for-loops, one after the other: the first time, skip all the elements that are arrays, and the second time, skip all the elements that aren't. This can avoid expensive comparisons in many cases.)
It should also be clear that the above will never return false when it should return true, since it only returns false when it finds an actual difference.
Lastly, I think it should be clear that the above will never return true when it should return false, since for every pair of objects, one full loop is always made over all the elements. This part is trickier to prove, but in essence, we've defined structural equality in such a way that two arrays are only structurally unequal if we can find some difference between them; and the above code does eventually examine every element of every array it encounters, so if there were a findable difference, it would find it.
Notes:
I didn't worry about arrays of primitives, int[] and double[] and so on. Adam's answer raises the possibility that you would want these to be compared elementwise as well; if that's needed, it's easily added (since it wouldn't require recursion: arrays of primitives can't contain arrays), but the above code just uses Object.equals(Object) for them, which means reference-equality.
The above code assumes that Object.equals(Object) implements a symmetric relation, as its contract specifies. In reality, however, that contract is not always fulfilled; for example, new java.util.Date(0L).equals(new java.sql.Timestamp(0L)) is true, while new java.sql.Timestamp(0L).equals(new java.util.Date(0L)) is false. If order matters for your purposes — if you want equal(new Object[]{java.util.Date(0L)}, new Object[]{java.sql.Timestamp(0L)}) to be true and equal(new Object[]{java.sql.Timestamp(0L)}, new Object[]{java.util.Date(0L)}) to be false — then you'll want to change ArrayPair.equals(Object), and probably ArrayPair.hashCode() as well, to care about which array is which.
You could add all visited objects to a temporary Map<Object, Object> structure to make sure, that you do not visit/inspect them again. The value is always a new Object, which will be used to replace already visited instances in your result lists.
Every time you see an object,
Check, if the map contains the instance
if not, put it to the map, the map value is a new Object
if yes, use the map value (the unique, new Object) in your list (xs or ys)
In your example, the result lists should look like this (pseudo language):
xs == {o1, "A", obj2} // obj2 == map.get(o2);
ys == {o2, "A", obj1} // obj1 == map.get(o1);
This will prevent from infinite loops.
I wrote this helper function to flatten each of the arrays and replaced its own reference with a string (or any primitive) for each level. The map will use a key-value store to keep track of the existing array objects (new at initialization). Assuming you have only arrays and comparable objects in the original array, you can compare the two flattened lists (with the same start level) without having to worry about infinite loops. This comparison should be linear.
private List<Object> flatten(Object[] array, Map<Object, String> map, int level) {
List<Object> list = new ArrayList<>();
for (Object o : array) {
if (o instanceof Object[]) {
if (map.get(o) != null) {
list.add(map.get(o));
} else {
map.put(array, "level"+level);
List<Object> flattened = flatten((Object[]) o, map, level+1);
for (Object obj : flattened)
list.add(obj);
}
} else {
list.add(o);
}
}
return list;
}
hope this helps.
I think I've managed it, at least works in all test cases I've tried so far. Please can someone confirm if my logic is OK. Needed to use the lesser-know IdentityHashMap to keep track of previously visited nodes by reference.
Not sure how to deal with nested arrays of other primitives like int[] etc. I added case for int[], but there are float, double, byte, short, long, boolean to add.
public static boolean deepEquals(Object [] o1, Object [] o2) {
return deepEquals(o1, o2, new IdentityHashMap<Object, Integer>());
}
public static boolean deepEquals(Object o1, Object o2, IdentityHashMap<Object, Integer> visited) {
if (! visited.containsKey(o1)) {
visited.put(o1, 0);
} else {
visited.put(o1, visited.get(o1) + 1);
}
if (! visited.containsKey(o2)) {
visited.put(o2, 0);
} else {
visited.put(o2, visited.get(o2) + 1);
}
boolean ret = false;
if (o1 == o2) {
ret = true;
} else if (o1 instanceof Object[] && o2 instanceof Object[]){
Object [] a1 = (Object[]) o1;
Object [] a2 = (Object[]) o2;
if (a1.length != a2.length ) {
ret = false; // different length, can't be equal
} else if (visited.get(o1) > 0 || visited.get(o2) > 0) {
ret = true; // been here before, stop searching
} else {
ret = true;
for (int i = 0; i < a1.length; i++) {
if (! deepEquals(a1[i], a2[i], visited)) {
ret = false;
break;
}
}
}
} else if (o1 instanceof int[] && o2 instanceof int[]){
ret = Arrays.equals((int[])o1, (int[])o2);
} else if (o1 == null && o2 == null){
ret = true; // null = null?
} else {
ret = o1.equals(o2); // just use equals
}
return ret;
}

Categories

Resources