Java的:实现equals方法比较两个双[] []数组 [英] Java: Implementing equals method for comparing two double[][] arrays
问题描述
我想实现我的类equals方法..
注意: _data code>属性是
双击[] []
排列IM试图在两个物体之间的比较。
反正编译和一切,但我总是得到一个错误的答案,这不可能是因为这两个数组是相同的:○
我做错了什么?还有没有其他简单的方法? (仅适用于使用从对象类的equals !!)
我的code(JAVA):
公共布尔等于(obj对象){
如果(!(OBJ的instanceof MyClass的)){
返回false;
} MyClass的MyObj中=(MyClass的)目标文件;
返回this._data.equals(myObj._data);
}
我会在你的MyClass的类重写equals方法。
@覆盖
公共布尔等于(obj对象){//如果您在使用一个对象作为参数,而不是双[] []坚持
如果(!(OBJ的instanceof MyClass的)){
返回false;
} MyClass的MyObj中=(MyClass的)目标文件;
如果(_data.length == myObj._data.length){
的for(int i = 0; I< _data.length;我++){
如果(_data [I]。长度== myObj._data [I]。长度){
对于(INT J = 0; J< _data [I]。长度; J ++){
如果(_data [I] [J]!= myObj._data [I] [J]){
返回false;
}
}
}其他{
返回false;
}
}
}其他{
返回false;
}
返回true;
}
这code考虑的情况下,你将有一个二维数组,但不是一个方阵。即第一行包含三个元素,第二排有27个要素,第三行有N个元素...
例如,一个测试用例:
双击[] [] =首新的双[5] [3];
双[] [] =第二个新的双[5] [3];
的for(int i = 0; I< first.length;我++){
对于(INT J = 0; J<第[I]。长度; J ++){
第[I] [J] = 5;
}
}
的for(int i = 0; I< second.length;我++){
为(中间体J = 0; J<第二[Ⅰ]。长度; J ++){
第二[I] [J] = 5;
}
}
第二[4] [2] = 2; MyClass的C1 =新MyClass的(第一);
MyClass的C2 =新MyClass的(第二); 的System.out.println(等于+ c1.equals(C2));
I'm trying to implement the equals method in my class..
notice: the '_data
' property is an double[][]
array im trying to compare between the two objects.
anyway it compiles and everything but i always get a false answer and this can't be because both arrays are same :o
am i doing something wrong? is there any other easy way? (only with using equals from object class!!)
My code (JAVA):
public boolean equals(Object obj) {
if (!(obj instanceof MyClass)) {
return false;
}
MyClass myObj = (MyClass) obj;
return this._data.equals(myObj._data);
}
I would override the equals method in your MyClass class.
@Override
public boolean equals(Object obj) {//if you insist in using an Object as argument instead of double[][]
if (!(obj instanceof MyClass)) {
return false;
}
MyClass myObj = (MyClass) obj;
if(_data.length == myObj._data.length){
for(int i=0; i<_data.length; i++){
if(_data[i].length == myObj._data[i].length){
for(int j=0; j<_data[i].length; j++){
if(_data[i][j] != myObj._data[i][j]){
return false;
}
}
}else{
return false;
}
}
}else{
return false;
}
return true;
}
This code considers the case you will have a two dimensional array but not a square matrix. i.e. first row with three elements, second row with 27 elements, third row with N elements... For example, a test case:
double[][] first= new double[5][3];
double[][] second= new double[5][3];
for(int i=0; i<first.length; i++){
for(int j=0; j<first[i].length; j++){
first[i][j] = 5;
}
}
for(int i=0; i<second.length; i++){
for(int j=0; j<second[i].length; j++){
second[i][j] = 5;
}
}
second[4][2] = 2;
MyClass c1 = new MyClass(first);
MyClass c2 = new MyClass(second);
System.out.println("Equals: "+c1.equals(c2));
这篇关于Java的:实现equals方法比较两个双[] []数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!