我需要在 java 中通过引用传递一个整数。有没有一种简单的方法可以做到这一点?在 C++ 中,通过在整数之前放置“&”将通过引用传递。 这是我试图转换为 Java 的 C 代码:
void count(int distance, int i, int &counter, int array[], int n) {
if (i == distance)
counter++;
else {
for (int j = 0; j < n; j++) {
if (i <= distance - array[j])
count(distance, i + array[j], counter, array, n);
}
}
}
有没有办法在没有整数对象的情况下做到这一点? (我不想再上一个类)
最佳答案
您将需要一个对象,但您不必自己构建它。 如Andy Turner said ,您可以使用 int 数组或 AtomicInteger所以:
int[] counter = new int[]{0};
counter[0]++;
..
AtomicInteger counter = new AtomicInteger();
counter.incrementAndGet();
或
您可以使用MutableInt在 commons-lang package
MutableInt counter = new MutableInt();
counter.increment();
关于java - java中通过引用传递一个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60434502/