何时包括什么? [英] When to include what?

查看:121
本文介绍了何时包括什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个类 Person (如书中所述)来保存从键盘输入的人的名字和姓氏,然后有另一个类 PhoneNumber ,它把国家代码,地区代码和人的数字封装为一个字符串。

Person用来作为HashMap中的密钥。< br>
Class BookEntry 封装了 Person PhoneNumber 。很多 BookEntry 对象组成了一个表示电话簿的HashMap。



Person implements Comparable< Person> ,因此它包含 CompareTo(Person)方法。后来这本书增加了 equals(Object anotherPerson)方法。

我的问题是,不是 CompareTo 足以比较两个键的方法吗?还是HashMap<>的内部机制要求我包含 equals()方法来比较两个键?

compareTo( )

  public int compareTo(Person person){
int result = lastName.compareTo(person。姓);
返回结果== 0? firstName.compareTo(person.firstName):结果;

等于()

  public boolean equals(Object anotherPerson){
return compareTo((Person)person)== 0;


解决方案

compareTo()方法用于排序,

这个方法的实现将决定谁在两个人之间更大(更小,相同)什么程度



while equals()& hashcode()将用于您的案例中基于Hash的数据结构(HashMap)中


<用户定义的类作为HashMap的关键字

是的,你需要实现 hashcode() code>和 equals()正确



另见




I created a class Person (as the book says) to hold the name and last name of a person entered from the keyboard and then there is another class PhoneNumber which encapsulates the country code, area code and the number of a person as a String.
Person is intended to be used as the key in a Hashmap.
Class BookEntry encapsulates both Person and PhoneNumber. A lot of BookEntry objects make up a HashMap that represents a phonebook.

Person implements Comparable<Person> so it contains CompareTo(Person) method. Later the book adds equals(Object anotherPerson)method.
My question is, isn't the CompareTo method enough for comparing two keys? or is it that the internal mechanics of the HashMap<> requires me to include equals() method to compare two keys?
compareTo()

public int compareTo(Person person) {
    int result = lastName.compareTo(person.lastName);
    return result==0? firstName.compareTo(person.firstName):result;
}

equals()

public boolean equals(Object anotherPerson){
    return compareTo((Person)person)==0;
}

解决方案

compareTo() method is used in sorting,

This method's implementation will determine who is greater(lesser, same) between two person, also at what degree

while equals() & hashcode() will be used in Hash based data structure (HashMap) in your case

user-defined class as a key of HashMap

yes you need to implement hashcode() and equals() properly

Also See

这篇关于何时包括什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆