==与equal的比较

来源:互联网 发布:手游防御矩阵攻略 编辑:程序博客网 时间:2024/04/30 06:25
package com.test;public class IndexofTest { public static void main(String[] args)  {  //基本类型比较  int a1=1;  int a2=1;  System.out.println("String型的\t'=='是\t"+(a1==a2)+"基本类型不能用’equal'");  //两个字符串比较  String s1="hello";  String s2="hello";  System.out.println("String型的\t'=='是\t"+(s1==s2)+"  'equal'是"+s1.equals(s2));  //这个比较特殊,当Integer在-128到127之间的时候,内存中开辟了一块位置存储数据,  Integer t1=345;  Integer t2=345;  System.out.println("Integer型的\t'=='是\t"+(t1==t2)+"  'equal'是"+t1.equals(t2));  //比较对象  test o1=new test("zhangsan",23);  test o2=new test("zhangsan",23);  System.out.println("Object的 \t'=='是\t"+(o1==o2)+"  'equal'是"+o1.equals(o2));    }}//测试用的类class test{private String name;private int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "test [age=" + age + ", name=" + name + "]";}public test(String name, int age) {super();this.name = name;this.age = age;}}

 

结果是:

String型的 '=='是 true基本类型不能用’equal'
String型的 '=='是 true  'equal'是true
Integer型的 '=='是 false  'equal'是true
Object的  '=='是 false  'equal'是false

原创粉丝点击