有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

C++中java的整数

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

有没有一种方法可以在没有整数对象的情况下执行此操作??(我不想再上一节课了)


共 (6) 个答案

  1. # 1 楼答案

    在java中,基本变量总是与“按值传递”绑定。如果要实现按引用传递功能,需要借助对象传递这些值。你可以看看这个链接上的例子:-Call by Value and Call by Reference in Java

  2. # 2 楼答案

    在Java中,通过引用传递基元类型的唯一方法是将其包装在对象中。基本上,不能通过引用传递基元类型,因为它们不是面向对象的

    查看此帖子以了解更多信息:How do I pass a primitive data type by reference?

  3. # 3 楼答案

    can't pass by reference in 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;
      }
    }
    
  4. # 4 楼答案

    正如您所知,Java是基本数据类型的传递值(即使对于类似包装器的整数) 单向-传递以i为实例成员的类对象。 另一种方法是将i作为类的实例成员,而不将i作为方法参数传递

  5. # 5 楼答案

    您可能需要有方法返回计数器

    我不确定这是同一个算法,但这是我心中的一个例子:

    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;
    }
    
  6. # 6 楼答案

    你需要一个对象,但你不必自己构建它。 作为Andy Turner said,可以使用int数组或AtomicInteger,所以:

    int[] counter = new int[]{0};
    counter[0]++;
    

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

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

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