命令行编译java文件、运行java:
//在所在文件目录路径下
javac test.java
//编译后,运行
java test
lit != null、!list.isEmpty()和list.size()>0的区别:
如果list==null,那么它根本就没有在堆上存在,即还未进行初始化,此时调用任何方法都会抛出空指针异常;
list.size == 0,则表示该list已经new过,只是其中没有存入任何值;
isEmpty()实际上是获取size的值进行判断再返回,list.size()是直接返回属性size的值;
//isEmpty()的源码
public boolean isEmpty() {
return size == 0;
}
作个比喻:1.有没有瓶子list != null;
2.瓶子里有没有水,list.isEmpty()或list.size > 0,判断前需要有瓶子,如果瓶子都没有会报nullException;
3.list.add(null)会造成list.isEmpty()为false,list.size()为1,所以要避免list.add(null)陷阱;
String理解和相关易错点
字符串常量池
String类是平时项目中使用频率非常高的一种对象类型,jvm为了提升性能和减少内存开销,避免字符串的重复创建,其维护了一块特殊的内存空间,即字符串池,当需要使用字符串时,先去字符串池中查看该字符串是否已经存在,如果存在,则可以直接使用,如果不存在,则将该字符串放入字符串常量池中;
使用String直接赋值
String str = "abc";可能创建一个或者不创建对象,如果"abc"在字符串中不存在,会在java字符串常量池中创建一个String对象("abc"),然后str指向这个内存地址,无论以后用这种方式,创建多少个值为"abc"的字符串对象,始终只有一个内存地址被分配。==判断的是对象的内存地址,而equals判断的是对象内容
String str = "abc";
String str1 = "abc";
String str2 = "abc";
System.out.println(str == str1);//true
System.out.println(str == str2);//true
另一种表述:
String str = “abc"
先在java的常量池中寻找"abc"对象,如果没有,在堆内存中new一个"abc"的对象,放到常量池中,之后在用直接赋值的方法时,如果值相同,就直接引用这个对象,不用新建,即直接赋值的值相同,那么它们两个就是同一个对象;
String str1 = "abc";
String str2 = "abc";
System.out.println(str1 == str2);//true
使用new String创建字符串
String str = new String("abc")
新建对象是直接在堆内存中新建一个对象,再赋值,用new新建对象的对象都不是同一个对象;
使用String字符串拼接
除了直接使用=复制,也会用到字符串拼接;字符串拼接又分为变量拼接和已知字符串拼接;
- 字符串如果是变量拼接,先开空间,再拼接;
- 字符串如果是常量相加,是先加,然后在常量池中找,如果有就直接返回,否则就创建;
String s1 = "hello";//常量池中创建hello
String s2 = "world";//在常量池中创建world
String s3 = "helloworld";//常量池中创建helloworld
String s4 = "hello" + "world";
System.out.println(s3 == s1 + s2);//false 变量拼接,先开空间,再拼接
System.out.println(s3 == s1 + "world");//false 变量拼接,先开空间,再拼接
System.out.println(s3 == "hello" + "world"); //true 拼接之后还是"helloworld",所以还是指向字符串常量池中的内存地址
System.out.println(s3 == s4); //true,同s3 == "hello" + "world"
在项目中建议尽量不要用new String去创建字符串,最好使用String直接赋值;
==和equals()
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println("s1 == s2");//false
Sytem.out.println(s1.equals(s2));//true
String s3 = new String("hello");
String s3 = "hello";
System.out.println(s3 == s4);//false
System.out.prtinln(s3.equals(s4));//true
String s5 = "hello";
String s6 = "hello";
System.out.println(s5 == s6);//true
System.out.println(s5.equals(s6));//true
网友评论