代码之家  ›  专栏  ›  技术社区  ›  hdw3

为什么对象?等于(对象O)需要Java中的对象?HASCODE()?[副本]

  •  0
  • hdw3  · 技术社区  · 6 年前

    Person 包装类

    List<Person> people = Arrays.asList(new Person("Kowalski"),
                                        new Person("Nowak"),
                                        new Person("Big"),
                                        new Person("Kowalski"));
    
    List<Person> distPeople = people.stream()
            .map(Wrapper::new)
            .distinct()
            .map(Wrapper::unwrap)
            .collect(Collectors.toList());
    

    distinct()

    返回由不同元素组成的流(根据

    Wrapper 那不管用(我用两个

    public class Wrapper
    {
        private final Person person;
    
        Wrapper(Person p)
        {
            person = p;
        }
    
        public Person unwrap()
        {
            return person;
        }
    
        public boolean equals(Object other)
        {
            if(other instanceof Wrapper)
                return ((Wrapper) other).person.getName().equals(person.getName());
            else
                return false;
        }
    }
    

    实施 添加此项后类工作:

    @Override
    public int hashCode()
    {
        return person.getName().hashCode();
    }
    

    hashCode() 包装 作品?

    3 回复  |  直到 6 年前
        1
  •  2
  •   Prashant    6 年前

    答案就在课堂上 DistinctOps makeRef 用于返回的实例 ReferencePipeline LinkedHashSet reduce 操作以获取不同的元素。注意 扩展自 HashSet 哪些用途 HashMap 哈希图 hashCode() 哈希代码() equals() hasCode() 以便 Stream#distinct()

        2
  •  2
  •   Thiru    6 年前

    从JavaDoc

    对于hashcode方法,它声明相等的对象必须具有

    here

        3
  •  2
  •   Floern    6 年前

    这个 distinct() HashSet 哈希集 hashCode() 其要素方法 to sort them into buckets

    哈希代码() equal() 哈希集