在Java中合并两个对象 [英] Merging two objects in Java
本文介绍了在Java中合并两个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个相同类型的对象。
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}
obj2 => {a=null;b= new ArrayList();c=default value}
可以请让我知道将这些对象组合成单个对象的最佳方法是什么?
Can you please let me know what is the best way to combine this objects into single object?
obj3 = {a = "hello";b=(same arraylist from obj2);c=10}
推荐答案
也许类似
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
可能会返回新的一个
对象而不是修改当前值。
A.merge
might return a new A
object instead of modifing current.
这篇关于在Java中合并两个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文