本文介绍了如何在Java中实现int in/out参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问这样一个原始问题的道歉.

Apologies for asking such a primitive question.

我写了一个带有一个参数的函数;该参数应该是输入/输出参数.

I wrote a function which took one parameter; this parameter was supposed to be an in/out parameter.

调试之后,我意识到,由于Java中没有显式的引用类型,所以我可能应该使用Integer对象(而不是int原始类型)作为参数类型.所以我改变了功能:

After debugging, I realized, since there are no explicit reference types in java, I should probably use Integer object (instead of int primitive) as the parameter type. So I changed my function:

boolean getNextFoo(int currentFoo) {
    currentFoo = currentFoo + 1;
}

收件人:

boolean getNextFoo(Integer currentFoo) {
    currentFoo = currentFoo + 1;
}

检查调试器中的执行后,我意识到这与以前的结果相同.也就是说,我传递给 getNextFoo()的对象不会更改.

After checking the execution in the debugger, I realized this has the same results as the previous. That is, the object that I'm passing into getNextFoo() does not change.

问题1 :如何使用Java实现输入/输出参数(特别是针对原始类型).我以为(请原谅)对象总是通过引用传递的.

Question 1: How to I achieve in/out parameters with Java (more specifically for primitive types). I thought (pardon me) that objects are always passed by reference.

问题2 :我正在互联网上查看答案,并看到Integer是不可变的.我了解不可变的意思是不变的.如果是这样,当我在 getNextFoo 函数中执行 currentFoo = currentFoo + 1 时,为什么编译器(解释器)没有抱怨?

Question 2: I was checking on the internet for answers and read that Integer is immutable. I understand immutable means constant. If so, why doesn't the compiler (interpreter?) complain when I do currentFoo = currentFoo + 1 within the getNextFoo function?

PS :我在调试器中看到Integer对象实际上没有传递给 getNextFoo ,而是 Integer.valueOf 的值是被传递到 getNextFoo 中,这让我更加困惑.

PS: I see in the debugger that Integer object is actually not being passed to getNextFoo, instead the value of Integer.valueOf is being passed into getNextFoo which is leaving me even more confused.

推荐答案

答案1:

一种方法是传入可变的 AtomicInteger .

boolean getNextFoo(AtomicInteger foo) {
  foo.set(foo.get() + 1);
  return true;
}

答案2:

以下语句: currentFoo = currentFoo + 1 并未修改对象;它正在创建一个新的Integer实例,并重新分配本地引用以指向它.

The statement: currentFoo = currentFoo + 1 is not modifying the object; it is creating a new Integer instance and reassigning the local reference to point to it.

从方法中退出时,本地引用丢失"(即超出范围),因此重新分配它在该方法之外无效.

When you exit from the method the local reference is "lost" (i.e. it goes out of scope) and hence reassigning it has no effect outside of the method.

这篇关于如何在Java中实现int in/out参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 02:50