`
talentkep
  • 浏览: 100474 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

任意2个对象的比较 Object Compare

J# 
阅读更多
直接上源码:

先来测试用的例子类:
public class A {

int count;
private String name;
private A aa = null;
public A(int count){
this.count=count;
}
public A getAa() {
return aa;
}

public void setAa(A aa) {
this.aa = aa;
}
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
public A(int count,String name){
this.count=count;
this.name=name;
}

public boolean equals(Object obj){
if (obj == this){
return true;
}
if (obj!=null && obj.getClass() == A.class){
A a = (A)obj;
if (this.count == a.count){
return true;
}
}
return false;
}

public int hashCode(){
return this.count;
}
}

再来Main函数
public static void main(String[] args) {
showNameAndValue(name, value);

System.out.println("===test object compare===");
String test1 = "Peter_Keasfasdf";
String test2 = "Peter_Keasfasdf";
Double int1 = new Double(10123.25);
Double int2 = new Double(20);
Date date1= new Date();
Calendar cal1 = Calendar.getInstance();
//cal1.add(Calendar.SECOND,2);
Calendar cal2 = Calendar.getInstance();
A b1 = new A(30,"Hello_world");
A b2 = new A(40,"Hello_World");
A a1= new A(10,"Peter_Ke");
A a2= new A(10,"Peter_Ke");
a1.setAa(b1);
a2.setAa(b2);

List l1 = new ArrayList();
List l2 = new ArrayList();
l1.add("aaa");
l1.add("bbb");
l1.add("CCC");
l2.add("aaa");
l2.add("bbb");

Date date2 = new Date(cal1.getTimeInMillis());
try {
//SimpleObjectCompare(test1,test2);
if (ObjectCompare(a1,a2)) System.out.println("---final test is equal");
else System.out.println("---final test is diff");
} catch (Exception e1) {
e1.printStackTrace();
}
}//end of main

重点来了 ObjectCompare

public static void DiffHandleAction(Object oldObj, Object newObj,Object oldObjField, Object newObjField, String fieldName,String type) {
System.out.println("---DiffHandleAction");
if (type == "simple") {
System.out.println("oldObj and newObj aren't equal: ");
System.out.println("oldObj is: "+oldObj);
System.out.println("newObj is: "+newObj);
}
if (type == "complex"){
//System.out.println("oldObj is: "+oldObj);
//System.out.println("newObj is: "+newObj);
System.out.println("oldObj and newObj aren't equal on field: "+fieldName);
System.out.println("oldObj on: "+fieldName+" value is: "+oldObjField);
System.out.println("newObj on: "+fieldName+" value is: "+newObjField);
}
if (type == "NotMatchType"){
//System.out.println("oldObj is: "+oldObj);
//System.out.println("newObj is: "+newObj);
System.out.println("oldObj and newObj aren not same class !");

}
System.out.println("---end DiffHandleAction");
}

public static boolean ObjectCompare (Object oldObj,Object newObj)throws Exception{
Class clazz = newObj.getClass();
boolean equalflag = true;
if (!oldObj.getClass().isInstance(newObj)){//if oldobj not the class newObj
//System.out.println("oldObj and newObj aren't same Class!");
DiffHandleAction(oldObj,newObj,null,null,null,"NotMatchType");
return false;
}
else{
//is simple object ?
if (oldObj instanceof Number || oldObj instanceof Collection || oldObj instanceof Boolean
|| oldObj instanceof String ||oldObj instanceof Date || oldObj instanceof Calendar){
System.out.println("oldObj and newObj are same Simple Objcet Class! Type is:" + oldObj.getClass().getName());
if (!SimpleObjectCompare(oldObj,newObj)){
/*System.out.println("oldObj and newObj aren't equal Simple Objcet:");
System.out.println("oldObj is: "+oldObj);
System.out.println("newObj is: "+newObj);*/
DiffHandleAction(oldObj,newObj,null,null,null,"simple");
return false;
}
}
//not simple object
else{
System.out.println("oldObj and newObj are complex Class!");
Field[] fields = oldObj.getClass().getDeclaredFields();
Object[] oldValue = new Object[fields.length];
Object[] newValue = new Object[fields.length];
String[] fieldNameArr = new String[fields.length];
//get object value if it accessable
for (int i = 0; i < fields.length; i++) {
fieldNameArr[i] = fields[i].getName();
System.out.println("check field:" + fieldNameArr[i]);
//try get field value
try {
oldValue[i] = fields[i].get(oldObj);
newValue[i] = fields[i].get(newObj);
} catch (IllegalAccessException e) {
System.out.println(fields[i].getName()+ " inaccessable but we try public get method");
//try get method
try {
Method[] methods = oldObj.getClass().getDeclaredMethods();
boolean found = false;
for (int j = 0; j < methods.length; j++) {
Method method = methods[j];
//find the get method
StringBuffer getMethodName = new StringBuffer("get");
getMethodName = getMethodName.append(fieldNameArr[i].substring(0,1).toUpperCase());
getMethodName = getMethodName.append(fieldNameArr[i].substring(1));
if (method.getName().compareTo(getMethodName.toString())==0){
found = true;
System.out.println("method.getName(): "+method.getName());
oldValue[i] = method.invoke(oldObj,null);
newValue[i] = method.invoke(newObj,null);
}
}
if (!found) System.out.println("No found get method! skip this field!");
} catch (Exception e1) {
System.out.println("Still can't get field value,skip this field!");
continue;
}
}//end try get field value

//String field
if (oldValue[i] instanceof String){
String oldString = (String) oldValue[i];
String newString = (String) newValue[i];
//not equal
if (!(oldString.compareTo(newString)==0)){
/*System.out.println("oldObj and newObj aren't equal on field: "+fieldNameArr[i]);
System.out.println("oldObj on: "+fieldNameArr[i]+" value is: "+oldString);
System.out.println("newObj on: "+fieldNameArr[i]+" value is: "+newString);*/
DiffHandleAction(oldObj,newObj,oldValue[i],newValue[i],fieldNameArr[i],"complex");
equalflag = false;
continue;
}
else{
//equal on this field
continue;
}
}
//end String field

//numble field
if (oldValue[i] instanceof Number){
Number oldNum = (Number) oldValue[i];
Number newNum = (Number) newValue[i];
//not equal
if (oldNum.doubleValue() != newNum.doubleValue()){
/*System.out.println("oldObj and newObj aren't equal on field: "+fieldNameArr[i]);
System.out.println("oldObj on: "+fieldNameArr[i]+" value is: "+oldNum);
System.out.println("newObj on: "+fieldNameArr[i]+" value is: "+newNum);*/
DiffHandleAction(oldObj,newObj,oldValue[i],newValue[i],fieldNameArr[i],"complex");
equalflag = false;
continue;
}
else{
// equal on this field
continue;
}
}//end numble field

//Date field
if (oldValue[i] instanceof Date){
Date oldDate = (Date) oldValue[i];
Date newDate = (Date) newValue[i];
//not equal
if (oldDate.compareTo(newDate)!=0){
/*System.out.println("oldObj and newObj aren't equal on field: "+fieldNameArr[i]);
System.out.println("oldObj on: "+fieldNameArr[i]+" value is: "+oldDate);
System.out.println("newObj on: "+fieldNameArr[i]+" value is: "+newDate);*/
DiffHandleAction(oldObj,newObj,oldValue[i],newValue[i],fieldNameArr[i],"complex");
equalflag = false;
continue;
}
else{
// equal on this field
continue;
}
}//end Date field

// Calendar field
if (oldValue[i] instanceof Calendar){
System.out.println("oldObj and newObj are Calendar!");
Calendar oldCalendar = (Calendar) oldValue[i];
Calendar newCalendar = (Calendar) newValue[i];
//not equal
if (newCalendar.getTime().compareTo(oldCalendar.getTime())==0){
/*System.out.println("oldObj and newObj aren't equal on field: "+fieldNameArr[i]);
System.out.println("oldObj on: "+fieldNameArr[i]+" value is: "+oldCalendar);
System.out.println("newObj on: "+fieldNameArr[i]+" value is: "+newCalendar);*/
DiffHandleAction(oldObj,newObj,oldValue[i],newValue[i],fieldNameArr[i],"complex");
equalflag = false;
continue;
}
else{
// equal on this field
continue;
}
}

//Boolean field
if (oldValue[i] instanceof Boolean){
Boolean oldBoolean = (Boolean) oldValue[i];
Boolean newBoolean = (Boolean) newValue[i];
//not equal
if (oldBoolean == newBoolean){
/*System.out.println("oldObj and newObj aren't equal on field: "+fieldNameArr[i]);
System.out.println("oldObj on: "+fieldNameArr[i]+" value is: "+oldBoolean);
System.out.println("newObj on: "+fieldNameArr[i]+" value is: "+newBoolean);*/
DiffHandleAction(oldObj,newObj,oldValue[i],newValue[i],fieldNameArr[i],"complex");
equalflag = false;
continue;
}
else{
// equal on this field
continue;
}
}//end Boolean field

//Collection field
if (oldValue[i] instanceof Collection){
Collection oldCollection = (Collection) oldValue[i];
Collection newCollection = (Collection) newValue[i];

//not equal size
if (oldCollection.size()!= newCollection.size()){
/*System.out.println("oldObj and newObj aren't equal on field: "+fieldNameArr[i]);
System.out.println("oldObj on: "+fieldNameArr[i]+" size is: "+oldCollection.size());
System.out.println("newObj on: "+fieldNameArr[i]+" size is: "+newCollection.size());*/
DiffHandleAction(oldObj,newObj,oldValue[i],newValue[i],fieldNameArr[i],"complex");
equalflag = false;
continue;
}

//equal size
if (oldCollection.size()== newCollection.size()){
//best way
if (oldCollection.containsAll(newCollection) && newCollection.containsAll(oldCollection)){
//Collection equeal
continue;
}
else{
/*System.out.println("oldObj and newObj aren't equal on field: "+fieldNameArr[i]);
System.out.println("oldObj on: "+fieldNameArr[i]+" value is: "+oldCollection);
System.out.println("newObj on: "+fieldNameArr[i]+" value is: "+newCollection);*/
DiffHandleAction(oldObj,newObj,oldValue[i],newValue[i],fieldNameArr[i],"complex");
equalflag = false;
continue;
}

//one way
/*Object[] newObjectArray = oldCollection.toArray();
Object[] oldObjectArray = newCollection.toArray();
for (int k = 0; k < oldObjectArray.length; k++) {
Object oldObjectElement = oldObjectArray[k];
Object newObjectElement = newObjectArray[k];
ObjectCompare(oldObjectElement,newObjectElement);
}*/

//Abandon method
/*Object[] newObjectArray = new Object[newCollection.size()];
Object[] oldObjectArray = new Object[oldCollection.size()];
int j=0;
for (Iterator iter = newCollection.iterator(); iter.hasNext();) {
Object element = (Object) iter.next();
newObjectArray[j] = element;
j++;
}
j=0;
for (Iterator iter = oldCollection.iterator(); iter.hasNext();) {
Object element = (Object) iter.next();
oldObjectArray[j] = element;
j++;
}

for (int k = 0; k < oldObjectArray.length; k++) {
Object oldObjectElement = oldObjectArray[k];
Object newObjectElement = newObjectArray[k];
ObjectCompare(oldObjectElement,newObjectElement);
}*/
}//end not equal size
}//end Collection field

//other Object field not String,not Number,not Collection,not Date,not Boolean
if (oldValue[i] instanceof Object){
//iterative
if (fieldNameArr[i].equalsIgnoreCase("class$0")) continue;
System.out.println("====iterative object here!!!! fieldName: "+fieldNameArr[i]);
Object oldObject= (Object) oldValue[i];
Object newObject = (Object) newValue[i];
if (!ObjectCompare (oldObject,newObject))equalflag = false;
System.out.println("====iterative object here!!!! fieldName: "+fieldNameArr[i]+" is:"+equalflag);
}//end other Object type

}//end for fields check
}//end not simple object judge
}//end same class type judge
return equalflag;
}// end of ObjectCompare method

public static boolean SimpleObjectCompare (Object oldObj,Object newObj)throws Exception{
if (!oldObj.getClass().isInstance(newObj)){//if oldobj not the class
   // newObj
//System.out.println("oldObj and newObj aren't same Class!");
DiffHandleAction(oldObj,newObj,null,null,null,"NotMatchType");
return false;
}
else{
//String Object
if (oldObj instanceof String){
System.out.println("oldObj and newObj are String!");
String oldString = (String) oldObj;
String newString = (String) newObj;
//not equal
if (!oldString.equalsIgnoreCase(newString)){
/*System.out.println("oldObj and newObj aren't equal: ");
System.out.println("oldObj is: "+oldString);
System.out.println("newObj is: "+newString);*/
DiffHandleAction(oldObj,newObj,null,null,null,"simple");
return false;
}
}

//numble field
if (oldObj instanceof Number){
System.out.println("oldObj and newObj are Number!");
Number oldNum = (Number) oldObj;
Number newNum = (Number) newObj;
//not equal
if (oldNum.doubleValue() != newNum.doubleValue()){
/*System.out.println("oldObj and newObj aren't equal: ");
System.out.println("oldObj is: "+oldNum);
System.out.println("newObj is: "+newNum);*/
DiffHandleAction(oldObj,newObj,null,null,null,"simple");
return false;
}
}

//Date field
if (oldObj instanceof Date){
System.out.println("oldObj and newObj are Date!");
Date oldDate = (Date) oldObj;
Date newDate = (Date) newObj;
//not equal
if (oldDate.compareTo(newDate)!=0){
/*System.out.println("oldObj and newObj aren't equal: ");
System.out.println("oldObj is: "+oldDate);
System.out.println("newObj is: "+newDate);*/
DiffHandleAction(oldObj,newObj,null,null,null,"simple");
return false;
}
}

//Calendar field
if (oldObj instanceof Calendar){
System.out.println("oldObj and newObj are Calendar!");
Calendar oldCalendar = (Calendar) oldObj;
Calendar newCalendar = (Calendar) newObj;
//not equal
if (newCalendar.getTime().compareTo(oldCalendar.getTime())!=0){
/*System.out.println("oldObj and newObj aren't equal: ");
System.out.println("oldObj is: "+oldCalendar);
System.out.println("newObj is: "+newCalendar);*/
DiffHandleAction(oldObj,newObj,null,null,null,"simple");
return false;
}
}

//Boolean field
if (oldObj instanceof Boolean){
System.out.println("oldObj and newObj are Boolean!");
Boolean oldBoolean = (Boolean) oldObj;
Boolean newBoolean = (Boolean) newObj;
//not equal
if (oldBoolean == newBoolean){
/*System.out.println("oldObj and newObj aren't equal: ");
System.out.println("oldObj is: "+oldBoolean);
System.out.println("newObj is: "+newBoolean);*/
DiffHandleAction(oldObj,newObj,null,null,null,"simple");
return false;
}
}

//Collection field
if (oldObj instanceof Collection){
System.out.println("oldObj and newObj aren Collection!");
Collection oldCollection = (Collection) oldObj;
Collection newCollection = (Collection) newObj;

//not equal size
if (oldCollection.size()!= newCollection.size()){
/*System.out.println("oldObj and newObj aren't equal: ");
System.out.println("oldObj is: "+" size is: "+oldCollection.size());
System.out.println("newObj is: "+" size is: "+newCollection.size());*/
DiffHandleAction(oldObj,newObj,null,null,null,"simple");
return false;
}

//equal size
if (oldCollection.size()== newCollection.size()){
//best way
if (oldCollection.containsAll(newCollection) && newCollection.containsAll(oldCollection)){
//Collection equeal
return true;
}
else{
/*System.out.println("oldObj and newObj aren't equal: ");
System.out.println("oldObj is: "+oldCollection);
System.out.println("newObj is: "+newCollection);*/
DiffHandleAction(oldObj,newObj,null,null,null,"simple");
return false;
}
}
}
}
return true;
}
分享到:
评论

相关推荐

    java 通用比较类

    这个比较器可以接受任何具有`compareTo()`方法的对象,只要对应的属性是可比较的。 4. **使用通用比较器** 当你需要对一个集合进行排序时,可以将这个比较器传递给`Collections.sort()`或`Arrays.sort()`方法。...

    List对象排序通用方法

    2. **通用比较方法**:Java提供了`Comparable`接口,可以用来实现对象之间的比较。但是,并非所有对象都会实现`Comparable`接口,所以我们还需要提供一种灵活的方式来比较对象的特定属性。 3. **泛方法**:类似于...

    js中判断Object、Array、Function等引用类型对象是否相等

    在迭代中,我们还要注意的是,对象或者数组中的元素可能是一个任意值——除了原始类型值、object、arrray外,这个值还可能是一个方法、一个DOM对象或者window对象,可能你已经注意到了,有部分引用类型是不能进行...

    【05-面向对象(下)】

    •==和equals比较运算符:==要求两个引用变量指向同一个对象才会返回true。equals方法则允许用户提供自 定义的相等规则。 •Object类提供的equals方法判断两个对象相等的标准与==完全相同。因此开发者通常需要...

    List对象排序通用方法[参考].pdf

    对于自定义对象,如果想根据某个属性进行排序,我们需要提供一个`Comparator`来定义比较规则。 以`UserInfo`对象为例,如果我们想要根据`userId`属性排序,通常需要编写如下的`Comparator`: ```java Collections....

    珠峰培训第二周作业1

    6. **数组检测**:判断一个数据是否为数组实例,可以使用`Object.prototype.toString.call(value)`并比较结果是否等于`"[object Array]"`。 7. **异常捕获**:在JavaScript中,异常处理通常通过`try-catch`语句实现...

    java比较器.md

    `compare()` 方法遵循与 `Comparable` 中 `compareTo()` 相同的原则,但它是静态方法,可以接受任意类型的对象。 ##### 3.3 使用示例 假设我们有一个 `Person` 类,并且想根据姓名排序: ```java public class ...

    c# 实现IComparable、IComparer接口、Comparer类的详解

    在默认情况下,对象的...2.IComparer 在一个单独的类中实现,可以比较任意两个对象。一般情况下,我们使用 IComparable 给出类的默认比较代码,使用其他类给出非默认的比较代码。一、IComparable提供了一个方法int Com

    List数据字段排序不关注数据库,直接排序

    - **Comparator**: Java 提供的一个接口,用于比较两个对象的大小。实现此接口的类可以作为比较器来对 List 中的对象进行排序。 #### 排序原理 在 Java 中,我们可以利用 `Collections.sort()` 方法结合自定义的 `...

    4.串和数组.ppt

    3. Compare(StringDS s):比较两个StringDS对象,返回整数值表示比较结果。 4. SubString(int index, int len):返回从指定索引开始的长度为len的子串。 5. Concat(StringDS s):连接两个StringDS对象,生成新的...

    JAVA面霸2001版

    `&&`具有短路特性,如果第一个操作数为假,则不会计算第二个操作数,而`&`会始终计算两边的操作数。 【跳出多重嵌套循环】 要跳出多重嵌套循环,可以使用`break`语句配合标签(label)来实现。例如: ```java ...

    Java Unsafe类1

    结合这两个值,我们可以直接计算并访问数组中的任意元素,无需通过传统的索引访问方式。 3. 线程挂起与恢复: `Unsafe`类包含`park()`和`unpark(Thread thread)`方法,用于线程的挂起和恢复。`park()`方法会阻塞...

    JavaScript笔记

    |--x.toString():用于把一个 Number 对象转换为一个字符串,并返回结果 19.正则表达式对象:(专门用于查找和验证) reg.test(‘要验证的完整字符串’)匹配返回true,否则返回false 强调:如果正则表达式使用了^和$...

    数据结构与算法(C#实现)系列---二叉树.doc

    - `CompareTo(object obj)` 方法用于比较两个二叉树的大小。 - 如果两个二叉树为空,则认为它们相等;否则,按照键值、左子树、右子树的顺序进行比较。 #### 总结 本文档介绍了二叉树的基本概念以及如何使用C#...

    达内java课程-java核心编程10天

    - **概念**: `Comparable`接口定义了一个`compareTo()`方法来比较两个对象的顺序,而`Comparator`接口定义了`compare()`方法来比较两个对象。 - **用途**: 实现这两个接口可以方便地对对象进行排序。 #### Java中...

    Linq基础学习资料,通俗易懂

    - **接口方法 override int Compare(T x, T y) 说明**:用于比较两个`T`类型的对象。 - **List.Sort (IComparer) 方法**:用于对`List&lt;T&gt;`进行排序。 #### 6. 集合扩展方法 集合扩展方法提供了大量便捷的方法来操作...

    delphi Tlist详解

    它能够容纳任意类型的对象,并提供了许多方法来管理这些对象,包括添加、删除、排序等操作。`TList` 的主要优点在于其灵活性和效率,尤其适用于需要频繁添加或删除元素的应用场景。 #### 三、关键属性与方法 **1. ...

    SystemVerilog语言教程[文].pdf

    * Object-Oriented Programming(OOP):SystemVerilog支持面向对象的编程思想,能够更好地模拟复杂的系统。 SystemVerilog是一种功能强大且灵活的硬件描述语言,它可以满足复杂的设计需求,提高设计效率和质量。

Global site tag (gtag.js) - Google Analytics