栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Java中覆盖equals方法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Java中覆盖equals方法

//Written by K@stackoverflowpublic class Main {        public static void main(String[] args) {        // TODO pre 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++) {     boolean check = people.get(i).equals(people.get(y));     System.out.println("-- " + people.get(i).getName() + " - VS - " + people.get(y).getName());     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;    }    @Override    public 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;    }    @Override    public 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;    }}

Output:

`run:

– Subash Adhikari - VS - K false

– Subash Adhikari - VS - StackOverflow false

– Subash Adhikari - VS - Subash Adhikari true

– K - VS - StackOverflow false

– K - VS - Subash Adhikari false

– StackOverflow - VS - Subash Adhikari false

– BUILD SUCCESSFUL (total time: 0 seconds)`



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/392642.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号