java 返回多个对象吗,Java面向对象设计:在java中返回多个对象

本文探讨Java中对象传参与返回的挑战,尤其是在处理多个对象时。理解Java的值传递机制如何导致NullPointerException,并介绍如何通过组合对象或使用集合返回。特别提到了在函数中返回多个对象的解决方案,如使用Pair、Triple等。
摘要由CSDN通过智能技术生成

The below code in Java throws Null pointer exception.

public class New{

int i;

New(int i)

{

this.i = i;

}

public void func(New temp)

{

temp.i = 10;

temp = new New(20);

}

public static void main(String[] args)

{

New n = null;

n.func(n);

System.out.println("value "+ n.i);

}

}

The reason being, java passes objects references by value. If I wanted to return one object, then I can return it from the function.

But, If I have multiple objects, the only way I could return the object references is, by keeping them into another object, like having some container which has references to all the objects.

Is there a better way to do it?

In C++, I normally just pass the address of pointer to handle this scenario. If I wanted to just return two objects of a single type, creating a container and passing it is a over kill.

What is the problem with returning multiple objects from a function? Why cannot the semantics of the function in all these languages be changed?

解决方案

Most often you create an object to hold the combination of objects you want to return.

For a more general-purpose solution, you can either return a collection, and array or some sort of tuple, such as Pair, Triple, etc (the latter you will need to create).

Note, you don't generally pass a mutable object as a parameter, but return an immutable one:

public Pair getLowHighTemp() {

int low,hgh;

// do stuff...

return new Pair(low,hgh);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值