JAVA 传递原始类型作为函数调用的引用

JAVA Pass Primitive type as a Reference to function call

我是 java 的新手。我需要在函数 call.I 中传递原始类型值作为参考,不想 return 我从函数中获取值,因为它已经 return 一些对象。

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 中,原始类型总是按值传递。要通过引用传递,您应该定义一个 class 并将原始类型放入其中。如果你传递 Integer class 它不起作用,因为这个 class 是不可变的并且值不会改变。

您可以使用 int[] 类型的单一数组作为快速解决方案并增加其内部值。这不会改变数组本身,只会改变它的内容。

您知道 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();
   }
}