- String运算会产生新的String, 不会改变其原有的值
StringBuilder和StringBuffer会改变其原有的值, 所以循环内字符串运算推荐用StringBuilder
@Test
public void test() {
List<String> strings = new ArrayList<>();
strings.add("hehe");
for (String e: strings) {
e = e.toUpperCase();
e += "hehe";
}
for (String string : strings) {
System.out.println(string);
}
}
/*
运行结果:
hehe
*/
@Test
public void test() {
List<StringBuilder> strings = new ArrayList<>();
strings.add(new StringBuilder("hehe"));
for (StringBuilder e: strings) {
e.append("hehe");
}
for (StringBuilder string : strings) {
System.out.println(string);
}
}
/*
运行结果:
hehehehe
*/
- Integer对象 -128-127范围的数字 在IntegerCache里,调用时直接引用. 所以Integer Long String对象的比较,应该调用equals方法.
@Test
public void test() {
for (Integer integer = -129; integer <= 128; integer++) {
Integer j = integer.intValue();
if (integer != j)
System.out.println(integer + " " + j);
}
}
/*
运行结果:
-129 -129
128 128
*/
@Test
public void test() {
Integer aInteger = 2;
Integer bInteger = 2;
Integer cInteger = 200;
Integer dInteger = 200;
System.out.println(aInteger == bInteger);
System.out.println(cInteger == dInteger);
}
/*
运行结果:
true
false
*/
- 值传递和引用传递,对象在方法中都是引用传递。但是Integer等类型会自动拆装箱,String类型会产生一个新的String.所以这几个对象在方法中传递不会影响值.
class Person {
int age;
String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
@Override
public String toString() {
return "age: " + String.valueOf(this.age) + ", name: " + name;
}
}
@Test
public void test() {
int a = 1;
addOne(a);
System.out.println(a);
Person person = new Person(10, "child");
addTwo(person);
System.out.println(person);
}
private void addOne(int val) {
val += 1;
}
private void addTwo(Person person) {
person.age += 2;
}
/*
运行结果:
1
age: 12, name: child
*/