写代码的时候到现在还容易会犯的错误,一直没有记牢,总结一下。
按照我的理解,Java可以理解为都是传值的。但是参数分两种,引用类型和原始类型。
原始类型(int, long, float, double, boolean),本身就是数值。
引用类型的值本身是指向对象的地址,所以传到函数中的是源数据的地址,更改指向相同地址的成员数据的话将改变原来对象里的内容。特例是下例子中test2和test3中都将str的指针重新指向了新的对象,而不是更改源对象,所以源对象没有改变。Array数组,二维数组,三维数组都是应用型。
package leetCode;
public class Test {
public static void test(StringBuffer str) {
str.append(", World!");
}
public static void test2(StringBuffer str) {
str = new StringBuffer("Hello World!");
}
public static void test3(String str) {
str = "Hello World!";
}
public static void test4(String str) {
str.replace('l', 'o');
// nothing changes, because replace() returns a new string without
// modify the existing one
}
public static void main(String[] args) {
StringBuffer string = new StringBuffer("Hello");
test(string);
System.out.println(string);
StringBuffer string2 = new StringBuffer("Hello");
test2(string2);
System.out.println(string2);
String string3 = "Hello";
test3(string3);
System.out.println(string3);
String string4 = "Hello";
test4(string4);
System.out.println(string4);
}
}
结果:
Hello, World!
Hello
Hello
Hello