Tag: 传递值

Java是通过值传递还是通过引用传递或两者兼而有之?

考虑以下案例。 List listOne = new ArrayList(); List listTwo = new ArrayList(); listOne.add(1);I think this happens due to listOne.add(2); listOne.add(3); Collections.reverse(listOne); listTwo = listOne; //listTwo has same reference Collections.reverse(listOne); System.out.println(listOne); //out put [1, 2, 3] System.out.println(listTwo); // same out put Java is pass by value, where values (for non primitive types) happen to be references. 我认为这为这种情况提供了java的生存。 […]

Java – 方法调用后对象状态不会改变

初学java问题,但我无法理解如下所示的示例中的call-by-Value(或Reference)是如何工作的 – 为什么在我的自定义String对象退出方法后,String值不会被修改。 ? 与Date等其他类相同 public class StringMadness { public static void main(String[] args) { String s = “Native String”; CustomStringObject cs = new CustomStringObject(); System.out.println(“Custom String Before: ” + cs.str); hello(cs); System.out.println(“Custom String After: ” + cs.str); System.out.println(“Native String Before: ” + s); hello(s); System.out.println(“Native String After: ” + s); } private static void […]

困惑,java是否在传递对象引用时使用按值调用或按引用调用?

public class program1{ public static void main(String args[]){ java.util.Vector vc=new java.util.Vector(); vc.add(“111”); vc.add(“222”); functioncall(vc); vc.add(“333”); System.out.println(vc); } public static void functioncall(java.util.Vector vc){ vc=null; } } 上述程序的输出为[111,222,333]。 但是,当我运行以下程序时,输出为[333]。 当我们传递引用时会感到困惑,无论是按值调用还是按引用调用,它是如何工作的? 为什么 public class program1{ public static void main(String args[]){ java.util.Vector vc=new java.util.Vector(); vc.add(“111”); vc.add(“222”); functioncall(vc); vc.add(“333”); System.out.println(vc); } public static void functioncall(java.util.Vector vc){ vc.removeAllElements(); } }

有人可以向我解释在Java中传递“值”而不是“引用”背后的原因是什么?

我是Java的新手(多年来一直在写其他东西),除非我遗漏了一些东西(我很高兴在这里错了)以下是一个致命的缺陷…… String foo = new String(); thisDoesntWork(foo); System.out.println(foo);//this prints nothing public static void thisDoesntWork(String foo){ foo = “howdy”; } 现在,我很清楚(相当差的措辞)概念,在java中,一切都是通过“值”传递而不是“引用”,但String是一个对象,有各种各样的花里胡哨,所以,人们会期待与int不同,用户可以对传递给方法的东西进行操作(并且不会被overloaded =设置的值所困)。 有人可以向我解释这个设计选择背后的原因是什么? 正如我所说,我不是想在这里,也许我错过了一些明显的东西?

在比较Java中的整数包装器时,为什么128 == 128 false但127 == 127为真?

class D { public static void main(String args[]) { Integer b2=128; Integer b3=128; System.out.println(b2==b3); } } 输出: false class D { public static void main(String args[]) { Integer b2=127; Integer b3=127; System.out.println(b2==b3); } } 输出: true 注意:-128到127之间的数字为真。