java - java中通过引用传递一个整数

标签 java c++

我需要在 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();

您可以使用MutableIntcommons-lang package

MutableInt counter = new MutableInt();
counter.increment();

关于java - java中通过引用传递一个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60434502/

相关文章:

java - "The requested resource does not support http method ' GET '"- 但我 'm not using C# or asp.net, I' 是发出请求的人

Java从二进制结构化文件中读取错误的值

Java:简单的递归问题

java - if(false) 与 while(false) : unreachable code vs. 死代码

java - 确定服务实例是否正在运行并终止它

C++ 前向类声明

c++ - 使用 "near"作为变量名时出现编译器错误

c++ - 为什么 std::binary_search 的参数是前向迭代器?

C++ 将指针的指针设置为空?

c++ - QtCreator错误: QGroupBox: No such file or directory