(1)double类型的陷阱
public class DoubleTest {
/**
* 这个程序可能无法结束运行
*/
@Test
public void test(){
for(double x = 0.1; x != 10.0; x += 0.1){
System.out.println(x);
}
}
/**
* 结果有误差的
*/
@Test
public void test2(){
System.out.println(2 - 1.1); //0.8999999999999999
}
}
(2)不可变的字符串String
public class StringTest {
@Test
public void test(){
String str1 = "hello";
String str2 = str1.substring(0, 2);
System.out.println("str1:" + str1);
System.out.println("str2:" + str2);
}
}
String str1 = "hello";的工作流程如下:
在字符串共享池new一个“hello”对象,然后str1指向“hello”这个对象。
str1.substring(0, 2);的工作流程如下:
在字符串共享池new一个“he”对象,然后str2指向“he”这个对象。
所以,str1并没有发生改变。
(3)空串和null串
<span style="white-space:pre"> </span>@Test
<span style="white-space:pre"> </span>public void test2(){
<span style="white-space:pre"> </span>String emptyStr = "";
<span style="white-space:pre"> </span>String nullStr = null;
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>//emptyStr是一个字符串引用,指像一个""空字符串(包含0个字符)
<span style="white-space:pre"> </span>if(emptyStr.isEmpty()){
<span style="white-space:pre"> </span>System.out.println("emptyStr是一个空串");
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>//nullStr是一个字符串引用,指向null
<span style="white-space:pre"> </span>if(nullStr == null){
<span style="white-space:pre"> </span>System.out.println("nullStr是一个null对象");
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>//会报空指针异常
<span style="white-space:pre"> </span>if(nullStr.isEmpty()){
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
(4)长度为0的数组
@Test
public void test(){
int[] array = new int[0];
System.out.println(array.length); //0
}
array是一个数组对象,长度为0