Merging two objects in Java

前端 未结 8 772
离开以前
离开以前 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:10

    Maybe something like

    class A {
        String a;
        List<..> b;
        int c;
    
        public void merge(A other) {
            this.a = other.a == null ? this.a : other.a;
            this.b.addAll(other.b);
            this.c = other.c == 0 ? this.c : other.c;
        }
    }
    
    A a1 = new A();
    A a2 = new A();
    
    a1.a = "a prop";
    a2.c = 34;
    
    a1.merge(a2);
    

    A.merge might return a new A object instead of modifing current.

提交回复
热议问题