2013-05-15 21 views
-1
private static int test[] =new int[]{2}; 

public static void main(String[] args) { 
    System.out.println(test[0]); 
    test(test); 
    System.out.println(test[0]); 
} 
private static void test(int[] test3) { 
    test3[0]=test3[0]+12; 
} 

印刷:如何让变量的行为像数组一样?

2 
14 

我怎样才能做到这一点,而无需使用数组?如果我使用

private static int test = 2 

private static Integer test = 2 

它停留2

+3

使用保存一个int字段的自定义类,改变由现场保存的值。换句话说,这只能用于非不可变的引用类型,而不能用于基元。 –

+0

或者从方法返回一个值,并将返回值重新赋值给变量。 –

回答

0

这样做会改变方法不使副作用一样,最好的办法。像

private static int addTwelve(int value) { 
    return value + 12; 
} 

,然后分配该值时则该方法返回

test = addTwelve(test); //or just 'test += 12;' in this case 

由于Java使用传递值语义,则该整数的值传递给该方法,而不是变量(或参考变量)。当你改变方法中的变量时,它是只有在该方法中改变。它与数组一起工作的原因是数组是一个对象,当以一个对象作为参数调用一个方法时,该对象的引用被复制。

这也意味着你可以创建一个具有价值的属性的类并调用test方法与类的一个实例。它可能看起来像这样

public class TestClass { 
    private int test = 2; 
    //more if you need to. 

    public void setTest(int value) { 
     this.test = value; 
    } 
    public int getTest() { 
     return this.test; 
    } 
} 

而且方法:

private static void test(TestClass x) { 
    x.setTest(x.getTest() + 12); 
} 

addTwelve方法可以在TestClass甚至更​​好(取决于使用情况ofcourse)在类的addValue(int value)创建。

+0

好的非常感谢你,但只有一个值使用数组或创建类更有效? (较少的CPU功率) – user2387586

+0

@ user2387586没有什么区别,你永远不会注意到。在尝试提高效率之前,请始终尝试编写可读代码。如果性能永远成为问题,您可以尝试改进代码,即使在这种情况下,我几乎可以保证这种选择不会产生任何影响。 – MAV

0

你需要做的变量本身你的任务:

private static int test = 2; 

public static void main(String[] args) { 
    System.out.println(test); 
    test = test(test); 
    System.out.println(test); 
} 
private static int test(int test) { 
    return test+12; 
} 

或者,没有方法调用:

private static int test = 2; 

public static void main(String[] args) { 
    System.out.println(test); 
    test += 12 // this is the same as: test = test+12 
    System.out.println(test); 
} 
相关问题