[英]Compare Vectors of different types in Java
我有兩個這樣初始化的Java向量:
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));
我做的比較就是這樣
boolean equal = vInt.equals(vDouble); //equal = false
考慮到盡管向量類型不同,向量如何具有相同的值,我如何比較兩個向量並得到true
結果呢?
TIA,
您別無選擇,只能依次比較每個元素。 通用解決方案如下所示:
public static boolean compareArrays(List<Integer> vInt, List<Double> vDouble) {
if (vInt.size() != vDouble.size())
return false;
for (int i = 0; i < vInt.size(); i++) {
Integer iVal = vInt.get(i);
Double dVal = vDouble.get(i);
if (!iVal.equals(dVal))
return false;
}
return true;
}
附帶說明-除非真正需要同步訪問,否則不應該使用Vector
,而應使用ArrayList
。
自己進行比較。 請注意,這會導致轉換錯誤,例如,在大約2 53 double
之后, double
不再表示奇數。 因此,例如,我不建議將long
與double
進行比較。
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;
}
沒有做到這一點的好方法。 值100.0和100不相等。 您將必須繼承Vector並重寫equals。 在equals方法內部,您需要遵守Vector的equals常規協定,但是必須執行一些比較操作,如下所示:
if(vInt.size() == vDouble.size()){
for(int index = 0; index < vInt.size()){
if(vInt.get(index) - (int) vDouble.get(index) == 0){
//etc.
}
}
}
請注意,在此比較中, 100 - (int) 100.4d
將評估為true
。
我認為需要對其進行迭代,並進行如下比較。
package org.owls.compare;
import java.util.Arrays;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Integer intArr[] = {100, 200, 300};
Double doubleArr[] = {100.d, 200.0, 300.0};
Vector<Integer> v1 = new Vector<Integer>(Arrays.asList(intArr));
Vector<Double> v2 = new Vector<Double>(Arrays.asList(doubleArr));
boolean isSame = true;
for(int i = 0; i < v1.size(); i++){
int dval = (int)((double)v2.get(i));
if(!v1.get(i).equals(dval)){
isSame = false;
}
}
System.out.println("result >> " + isSame);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.