toString()使用:
public class Demo { public static void main(String[] args){ Student s1 = new Student(); System.out.println(s1); //自动执行s1.toString(); } } class Student{ private int id; private String name; public Student(){}; public Student(int id,String name){ this.id = id; this.name = name; } public String toString(){ //重写toString(),建议 return "id="+this.id+",name="+this.name; } }
equals使用:
字符串
public class Demo { public static void main(String[] args){ String a = new String("HH"); String b = new String("HH"); System.out.println(a==b); //false System.out.println(a.equals(b)); //true //字符串对象重写了equals方法 String c = "hh"; String d = "hh"; System.out.println(c==d); //true System.out.println(c.equals(d)); //true Integer a = 127; //Integer相当于引用和int基本数据类型不同 Integer b = 127; System.out.println(a==b); //true,由于享元模式,java解释器会缓存1个字节中的数,第二次创建127,就直接 从缓存返回数据; System.out.println(a.equals(b)); //true Integer c = 128; Integer d = 128; System.out.println(c==d); //false,由于128大于一个字节,不缓存,就会每次新new出一个对象. System.out.println(c.equals(d)); //true } }
对象
public class Demo { public static void main(String[] args){ Student s1 = new Student(1,"hh"); Student s2 = new Student(); System.out.println(s1==s2); //false System.out.println(s1.equals(s2)); //false } }
如果需求是两个对象的传递的值是一样的,那么我们就认为两个对象是相等的,此时需要重写equals方法
public class Demo { public static void main(String[] args){ Student s1 = new Student(1,"hh"); Student s2 = new Student(1,"hh"); System.out.println(s1.equals(s2)); //true 重写了equals方法 } } class Student{ private int id; private String name; public Student(){}; public Student(int id,String name){ this.id = id; this.name = name; } public String toString(){ //重写toString(),建议 return "id="+this.id+",name="+this.name; } public boolean equals(Object obj){ //使用object接受 if(this == obj){ return true; } else{ if(obj instanceof Student){ Student s = (Student)(obj); if(s.id==this.id&&s.name.equals(this.name)){ return true; } } } return false; } }