How to Increment a class Integer references value in java from another method

后端 未结 10 637
攒了一身酷
攒了一身酷 2020-12-09 02:29
package myintergertest;

/**
 *
 * @author Engineering
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void          


        
10条回答
  •  悲哀的现实
    2020-12-09 03:08

    You are looking for something similar to C++'s reference or to C#' out parameter. Java (and many other languages) does not support this.

    This type of behavior is typically achieved by changing the method from void to (in this case) int: public static int increment(int n) { return ++n; }

    If the method is already returning something then you can create a new class that has two fields (can even be public): the original return value and the new value of n.

    Alternatively, you can also wrap the integer inside a generic Cell class. You only need to write this Cell class once:

    public class Cell {
      public Cell(T t) { value = t; }
      public void set(T t) { value = t; }
      public T get() { return value; }
    }
    

    You can then use it in all situations where you want to a method to change a primitive:

    public static void increment(Cell n) {
      n.set(n.get()++);
    }
    
    Cell n = new Cell(0);
    increment(n);
    increment(n);
    increment(n);
    System.out.println(n.get()); // Output: 3
    

提交回复
热议问题