Java中的equals与==

来源:互联网 发布:钢铁出口数据 编辑:程序博客网 时间:2024/06/04 19:37

Object类有boolean equals(Object obj)方法,实现为return this == obj。(==用于比较两者地址是否相同,就是两个变量是否引用了同一个对象)

如果子类想要用equals作为内容比较的方法,则要对Object类的boolean equals(Object obj)方法进行Override。

  1. 如果是基本类型比较,那么只能用==来比较,不能用equals,因为equals是对象方法。

    int a=10;int b=10;a==b;//返回是true
  2. 对于基本类型的包装类型,比如Boolean、Character、Byte、Shot、Integer、Long、Float、Double等的引用变量,==是比较地址的,而equals是比较内容的,因为它们的实现中Override了boolean equals(Object)方法

    String a= new String("abc");String b= new String("abc");a==b;//结果是falsea.equals(b);//返回true
  3. 对于自定义的对象类型,需要自己对boolean equals(Object)方法进行Override。下面是标准实现:

    //Written by K@stackoverflowpublic class Main {/** * @param args the command line arguments */public static void main(String[] args) {    // TODO code application logic here    ArrayList<Person> people = new ArrayList<Person>();    people.add(new Person("Subash Adhikari",28));    people.add(new Person("K",28));    people.add(new Person("StackOverflow",4));    people.add(new Person("Subash Adhikari",28));    for (int i=0;i<people.size()-1;i++){        for (int y=i+1;y<=people.size()-1;y++){            System.out.println("-- " + people.get(i).getName() + " - VS - " + people.get(y).getName());            boolean check = people.get(i).equals(people.get(y));            System.out.println(check);        }    }}}//written by K@stackoverflowpublic class Person {private String name;private int age;public Person(String name, int age){    this.name = name;    this.age = age;}// 这里@Overridepublic boolean equals(Object obj) {    if (obj == null) {        return false;    }    if (!Person.class.isAssignableFrom(obj.getClass())) {        return false;    }    final Person other = (Person) obj;    if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {        return false;    }    if (this.age != other.age) {        return false;    }    return true;}@Overridepublic int hashCode() {    int hash = 3;    hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0);    hash = 53 * hash + this.age;    return hash;}public int getAge() {    return age;}public void setAge(int age) {    this.age = age;}public String getName() {    return name;}public void setName(String name) {    this.name = name;}}
原创粉丝点击