zoukankan      html  css  js  c++  java
  • List中的Contains方法内部其实是用对象的equals方法做比较,所以如果比较两个类就重写类的equals方法即可;而Set是调用equals和hashCode

    public class Person {
    
        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;
        }
    
        @Override
        public boolean equals(Object obj) {
            Person person = (Person) obj;
            return this.name == person.getName();
        }
    
    //    @Override
    //    public int hashCode() {
    //        return 1;
    //    }
    }
    public class TestDemo {
    
        @Test
        public void func1(){
            Person person=new Person();
            person.setName("aaa");
            person.setAge(20);
    
            Person person1=new Person();
            person1.setName("aaa");
            person1.setAge(22);
    
            List<Person> personList=new ArrayList<Person>();
            personList.add(person);
            if(!personList.contains(person1)){
                personList.add(person1);
            }
            Set<Person> personSet=new HashSet<Person>();
            personSet.add(person);
            if(!personSet.contains(person1)){
                personSet.add(person1);
            }
    
            System.out.println("");
    
        }
    
    }

    打开Person类的hasCode注释后,运行如下

  • 相关阅读:
    当模型验证未通过时,获取未通过验证的属性
    在ASP.Net MVC中进行身份认证
    c#生成验证码
    HTTP与FTP状态码
    VUEX
    JS模块化
    Vue.JS入门下
    flex布局
    asp.net Web API
    JWT加密解密
  • 原文地址:https://www.cnblogs.com/hujiapeng/p/8436740.html
Copyright © 2011-2022 走看看