1 Integer与Integer间的比较,从jdk1.5开始,有“自动装箱”这么一个机制,在byte-128到127范围内(ps整型的八位二进制的表示的范围为-128到127),如果存在了一个值,再创建相同值的时候就不会重新创建,而是引用原来那个,但是超过byte范围还是会新建的对象。
来自 <http://blog.sina.com.cn/s/blog_7f033dcf01017ljx.html>
Integer a1=100;
Integer a2=100;
Integer a3=150;
Integer a4=150;
System.out.println(a1==a2);//(true)
System.out.println(a3==a4);// (false)
2 基本数据类型和对象比较的时候,对象会自动拆箱为基本数据类型再比较,比较的就是里面的值而不是地址
来自 <http://blog.sina.com.cn/s/blog_7f033dcf01017ljx.html>
Integeri1=newInteger(128);
inti2=128;
System.out.println(i1==i2);//true
3 //不会经历拆箱过程,i1的引用指向堆,而i2指向专门存放他的内存(常量池),他们的内存地址不一样,所以为false
来自 <http://blog.sina.com.cn/s/blog_7f033dcf01017ljx.html>
Integeri1=newInteger(128);
Integeri2=128;
System.out.println(i1==i2); // false
(注意2和3的区别)
4 //两个都是new,两个对象间的比较,比较的是地址,所以为false
来自 <http://blog.sina.com.cn/s/blog_7f033dcf01017ljx.html>
Integera1=new Integer(100);
Integera2=new Integer(100);
Integera3=new Integer(150);
Integera4=new Integer(150);
System.out.println(a1==a2);// (false)
System.out.println(a3==a4);// (false)
5 String类型
String a="123";
//在堆创建一个对象被b引用,然后堆中的值指向常量池的“123”
String b=new String("123");
//两者指向的地址不同,所以为false
Stringa="123";
Stringb=newString("123");
System.out.println(a==b); //false
System.out.println("---String与newString------"+a.equals(b));// true
来自 <http://blog.sina.com.cn/s/blog_7f033dcf01017ljx.html>
注:Object中的equal与==的作用相同,但是String类复写了Object类的equal方法,只要a和b的内容相同,则返回true
6 Integer的equals方法,比较的是内容
Integera1=newInteger(100);
Integera2=newInteger(100);
Integera3=newInteger(150);
Integera4=newInteger(150);
System.out.println(a1.equals(a2));// (true)
System.out.println(a3.equals(a4)); //(true)