在Java中通过引用传递一个整数。

5

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

有没有一种方法可以不使用整数对象来实现?(我不想创建另一个类)


4
你可以返回计数器,即int类型,而不是void。 - Bentaye
2
@SPlatten Java有Integer和int(整数)两种类型。第一个是int原始类型的对象。 - Reporter
1
这个回答解决了你的问题吗?Java是按引用传递还是按值传递? - Amongalen
@Bentaye 我并没有得到我需要的答案,但还是谢谢 :) - vanes
1
这个回答解决了你的问题吗?如何在Java中实现原始类型的引用传递 - Sharad Nanda
显示剩余7条评论
7个回答

4
你需要一个对象,但你不必自己构建它。 正如Andy Turner所说,你可以使用int数组或AtomicInteger,因此:
int[] counter = new int[]{0};
counter[0]++;

..

AtomicInteger counter = new AtomicInteger();
counter.incrementAndGet();

或者

你可以在 commons-lang 包 中使用 MutableInt

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

2

在Java中,你不能通过引用传递参数

你可以传递一个可变的容器,例如int[1]AtomicInteger

void count(int distance, int i, int[] counter, int array[], int n)

或者您可以使用返回值来返回counter的更新值:
int count(int distance, int i, int array[], int n) {
  if (i == distance) return 1;
  else {
      int counter = 0;
      for (int j = 0; j < n; j++) {
          if (i <= distance - array[j]) counter += count(distance, i + array[j], array, n);
      }
      return counter;
  }
}

值得一提的是,整数是不可变的,这就是为什么你不能简单地传递它的原因。 - Amongalen

2

你可能需要让你的方法返回计数器

我不确定这是否是相同的算法,但这是我想法的一个示例:

public static void main(String[] args) {
    int counter = 3;
    counter = count(2, 1, counter, new int[] {1,2,3}, 3);
    System.out.println(counter);
}

static int 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])
                counter = count(distance, i + array[j], counter, array, n);
        }
    }
    return counter;
}

我实际上认为你不想执行 counter += count(...)。我认为你只需要 = - Andy Turner
@AndyTurner 老实说,我不知道。 - Bentaye
@AndyTurner 好的,我成功运行了C++代码进行比较,你是对的,应该是= - Bentaye

1

在Java中,传递原始类型按引用的唯一方法是将其包装在对象中。从根本上讲,您不能传递原始类型按引用,因为它们不是面向对象的。

查看此帖子以获取更多信息:如何通过引用传递原始数据类型?


0

在Java中,原始变量始终与“按值传递”绑定。如果要实现按引用传递功能,则需要使用对象传递这些值。您可以查看此链接中的示例:Java中的按值调用和按引用调用


0

正如您所知,Java对于原始数据类型(甚至包装类如Integer)采用值传递方式。 一种方法是 - 传递一个具有i作为实例成员的类对象。 另一种方法是 - 将i作为类的实例成员,并且不将i作为方法参数传递。


0
一个不同的(功能性)解决方案,传递一个执行计数(或所需操作)的Runnable
void count(int distance, int i, Runnable counter, int array[], int n) {
    if (i == distance) {
        counter.run();
    }

这将被称为:

private int count;  // does not work with local variable
    // ...
    count(distance, i, ()->count++, array, n);

或者,使用一个方法:

    count(distance, i, this::increment, array, n);
    // ...
private void increment() {
    count++;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接