我是java的新手。我需要传递原始类型值作为函数调用中的引用。我不想从函数返回i值,因为它已经返回了一些对象。
for (int i = 0; i < objects.size();) {
// here it should fetch that object based on i manipulated in function
Object obj = objects.get(i)
Object node = someFunction(session,obj,i);
// push node in nodes array
}
public Object someFunction(Session session,Object obj,int i){
//manipulate i value based on condition
if(true){
i = i + 1;
}else{
i = i + 2;
}
}
我如何实现这一点,因为JAVA使用函数调用中的值传递?
谢谢
你知道java流吗?使用流可以执行以下操作:
List<Object> result = objects.stream()
.filter(object -> {/*add condition here*/})
.map(object->{/*do something with object that match condition above*/})
.collect(Collectors.toList());
您可以使用此机制根据特定条件收集和处理对象。
如果这没有帮助,可能使用迭代器?
Iterator<Object> it = objects.iterator();
while(it.hasNext()){
Object node = someFunction(session,it);
}
public Object someFunction(Session session,Iterator i){
//manipulate i value based on condition
if(true){
i.next();
}else{
i.next();
i.next();
}
}
在java原始类型中,始终按值传递。要通过引用传递,您应该定义一个类并将基本类型放入其中。如果传递Integer类,则它不起作用,因为此类是不可变的,并且值不会更改。
您可以使用int[]
类型的奇异数组来快速解决并增加其内部值。这不会改变数组本身,只改变其内容。