简体   繁体   中英

Passing dynamic primitive type (int) to a method

In Java, the output of s is 0. I do not understand why and would it be possible to somehow get the correct value of s (1000 here)?

public static void main(String args) {
    int s = 0;
    List<Integer> list = getList(s);
    System.out.println("s = " + s);
}

public static List<Integer> getList(int s) {

    List<Integer> list = new ArrayList<Integer>();
    for (int i = 0; i < 1000; i++) {
        list.add(i); s++;
    }
}

In C# there were out descriptors to indicate that the variable is going to change if I'm not mistaken..

I'm not going to get the list.size() in general!

In Java, all method arguments are passed by value, ie copy. So, changes to the copy are not visible to the caller.

To address your second question, you can just use list.size() on the caller side.

I see two ways

1) Make 's' as static variable and move it to class level

2) Create class with getter/setter for list and int and return the object for getList call

public static MyWrapperObj getList(int s) {

   ......
return wrapperObj
}

class MyWrapperObj 
{
private List<Integer>;
private countS;
....
//getter/setters.
}

Java doesn't allow for passing parameters by reference - but you could wrap it in an object like this:

class IntHolder {
        private int s;
        IntHolder(int s){
            this.s = s;
        }

        public void setS(int s){
            this.s = s;
        }

        public int getS(){
            return s;
        }

        public void increment(){
            s++;
        }
}

class Test{

  public static void main(String[] args) {
    IntHolder s = new IntHolder(0);
    List<Integer> list = getList(s);
    System.out.println("s = " + s.getS());
  }

  public static List<Integer> getList(IntHolder s) {

    List<Integer> list = new ArrayList<Integer>();
    for (int i = 0; i < 1000; i++) {
        list.add(i); s.increment();
    }
    return list;
  }
}

In java, arguments passed to methods are passed by value.. you will need to make sa global or instance variable in order to modify it in other methods. This is just the way java works. eg

public class Test{
     private int s;

     public Test(){
          s=0;
          increment();
          //print now will be 1000.
     }

     private void increment(){
          s = 1000;
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM