java 组合对象,在Java中合并两个对象

本文讨论如何在Java中合并两个具有相同类型的对象,特别是当对象包含基本类型和集合属性时。提出了一种通过`merge`方法实现对象属性合并的方案,该方法可以智能地处理null值和默认值。通过调用`merge`方法,对象的属性被有效地整合到一个新的或已存在的对象中。
摘要由CSDN通过智能技术生成

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}

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值