Compare vectors of different types in Java

advertisements

I have two Java vectors initialized like these:

Integer intArr[] = {100, 200, 300};
Double doubleArr[] = {100.0, 200.0, 300.0};

Vector<Integer> vInt = new Vector<Integer>(Arrays.asList(intArr));
Vector<Double> vDouble = new Vector<Double>(Arrays.asList(doubleArr));

The comparision that I do is like this

boolean equal = vInt.equals(vDouble);  //equal = false

How can I compare the two vectors and get true as result considering that, despite the different types, the vectors have the same values?

TIA,


Make the comparison yourself. Note this is subject to conversion errors, for example after around 253 double can no longer represent odd numbers. So I don't recommend comparing long to double, for example.

public static boolean numericEquals(
    Collection<? extends Number> c1,
    Collection<? extends Number> c2
) {
    if(c1.size() != c2.size())
        return false;
    if(c1.isEmpty())
        return true;

    Iterator<? extends Number> it1 = c1.iterator();
    Iterator<? extends Number> it2 = c2.iterator();

    while(it1.hasNext()) {
        if(it1.next().doubleValue() != it2.next().doubleValue())
            return false;
    }

    return true;
}