Merging two objects in Java

前端 未结 8 781
离开以前
离开以前 2020-12-15 23:25

I have two objects of same type.

Class A {
  String a;
  List b;
  int c;
}

A obj1 = new A();
A obj2 = new A();

obj1 => {a = \"hello\"; b = null; c = 10         


        
8条回答
  •  春和景丽
    2020-12-16 00:05

    In your very special case it looks like you want a new object that takes the real values from both instances. Here is an implementation that will do that. The method should be add to class A so that it can access the fields.

     public A specialMergeWith(A other) {
       A result = new A();
    
       result.a = (a == null ? other.a : a);
       result.b = (b == null ? other.b : b);
       result.c = (c == DEFAULT_VALUE ? other.c : c);
    
       return result;
     }
    

提交回复
热议问题