我知道java 中对象是引用传递的,以至于当方法a中一个对象作为参数传递给一个方法b时,当方法b中改变了这个对象,该对象a在方法a中也改变了;
而8中基本数据类型则不然;那么现在我要让8种基本数据类型也引用传递,如何写;
我有一个想法就是先把基本数据封装成类,可是按照如下写法不行,高手路过,请指点:
public class Test { static void fun(Integer a) {
a += 1;
}
public static void main(String[] args){
Integer a = new Integer(1);
System.out.println(a);
fun(a);
System.out.println(a);
}
}

解决方案 »

  1.   

    java 中对象是引用传递的
    java 中只有值传递的
    你用java的封装类是不能实现你的需求的
    你可以自己封装下
      

  2.   

    做不到,除非你把这些基本类型,放到自定义的类中,或者创建成数组。
     static void fun(Integer[] a) {
            a[0] += 1;
        }
        public static void main(String[] args){
            Integer[] a ={1};
            System.out.println(a[0]);
            fun(a);
            System.out.println(a[0]);
        }
      

  3.   

    不知道这样可以不
    另外纠正下 java 里是没有引用传递的
    当一个对象作为参数的时候
    传的是这个对象在堆中的地址
    你的方法只是改变了参数的属性值
    并没有改变参数的值public class Test { public static void main(String[] args) {
    Node a = new Node(1);
    System.out.println(a.getI());
    fun(a);
    System.out.println(a.getI());
    } static void fun(Node a) {
    a.setI(a.getI() + 1);
    }}class Node {
    private int i; public int getI() {
    return i;
    } public void setI(int i) {
    this.i = i;
    } public Node(int i) {
    this.i = i;
    }
    }
      

  4.   

    为了看起来舒服点 可以重写 toString 方法
    public class Test { public static void main(String[] args) {
    Node a = new Node(1);
    System.out.println(a);
    fun(a);
    System.out.println(a);
    } static void fun(Node a) {
    a.setI(a.getI() + 1);
    }}class Node {
    private int i; public int getI() {
    return i;
    } public void setI(int i) {
    this.i = i;
    } public Node(int i) {
    this.i = i;
    } @Override
    public String toString() {
    // TODO Auto-generated method stub
    return "" + this.i;
    }

    }
      

  5.   

    public class Test {    private Interger a;
        
        public void setA(Integer a)
        {
           this.a = a;
        }    public Integer getA()
        {
           return this.a;
        }    static void fun() {
            this.a += 1;
        }
        public static void main(String[] args){
            Integer a = new Integer(1);
            Test test = new Test();
            test.setA(a);
            System.out.println(a);
            test.fun(a);
            System.out.println(test.getA());
        }
    }
      

  6.   

    没啥好办法,这是java,只有些替代办法例如
    public class Test {    static Integer fun(Integer a) {
            return ++a;
        }
        public static void main(String[] args){
            Integer a = new Integer(1);
            System.out.println(a);
            a = fun(a);
            System.out.println(a);
        }
    }