java——容器

2017-04-22  本文已影响0人  exmexm

Collection接口--定义了存取一组对象的方法,
其子接口Set和List分别定义了存储方式。
其中Set中的数据对象没有顺序且不可重复。
List中的数据对象有顺序且可以重复。
注:重复的概念是指两个对象互相的equals。

Map接口定义了存储“键(key)--值(value)”映射对的方法。

图片.png

实现了Collection接口中所定义的方法:
int size()
boolean isEmpty()
void clear();
boolean cantains(object element)
boolean remove(object element)
Iterator iterator()
boolean cotainsAll(Collection c)
boolean addAll(Collection c)
boolean removeAll(Collection c)
boolean retainAll(Collection c)
Object[] toArray();

比较两个对象如果没有重写equals()方法的话,则直接调用父类的equals方法。
一般Object的equals方法是直接比较两个对象的引用是否相等。

容器类对象在 调用remove、contains等方法时需要比较对象是否相等,
这是涉及到对象类型的equals方法和hashCode方法;
对于自定义的类型,需要重写equals和hashCode方法来实现自定义的对象相等的规则。
注意:相等的对象应该具有相等的hashCode。

实现Name对象的equals方法重写。


public class Name {
    String firstName, lastName;
    
    Name(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    
    public String toString() {
        return firstName + " " + lastName;
    }
    
    public boolean equals(Object obj) {
        if (obj instanceof Name) {
            Name name = (Name) obj;
            return (firstName.equals(name.firstName)) && (lastName.equals(name.lastName));
        }
        return super.equals(obj);
    }
    
    public int hashCode() {
        return firstName.hashCode();
    }
}

关于hashCode和equals的参考:
http://blog.csdn.net/fenglibing/article/details/8905007

上一篇下一篇

猜你喜欢

热点阅读