Java LinkedHashMap为什么要实现Map接口?
ringa_lee
ringa_lee 2017-04-18 09:30:41
0
3
893

HashMap已经实现了Map接口,LinkedHashMap既然继承了HashMap,为什么还要implements一遍,是为了保留自己跟父类HashMap中Map方法不一样的可能性吗?如果是,那为什么不直接重写,还要再继承呢?

附:LinkedHashMap源代码

public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> {
/*
省略内部代码
*/
}
ringa_lee
ringa_lee

ringa_lee

reply all(3)
刘奇

There are many such writing methods in the Collection source code of JDK.
In fact, we have to admit that this way of writing has no side effects.
But there is an advantage to writing it like this, it can be opened separatelyLinkedHashMap的源码,你就知道了它继承了哪个类,并实现了哪个接口。换句话说,不用去点开HashMap的源代码才能知道原来LinkedHashMap实现了Map. That is, you don't have to worry about the inheritance relationship, especially when the inheritance relationship between classes is very complicated.

This for humane consideration, there are some examples, such as
an interface inherits the interface, but the sub-interface will explicitlydeclare all the methods in the parent interface, and explicitly add @Override This annotation specifically indicates that this method is inherited from the parent interface and has nothing to do with the interface I defined.

左手右手慢动作

In fact, this may be just a practice of Java developers.
Usually our requirements will say which interfaces a certain class needs to implement, but in fact, if we take the trouble to find the mutual dependencies of these interfaces and then eliminate duplicate projects, the process is cumbersome, and these duplicates will also be compiled during compilation. automatically processed. So these people directly write the classes that are required to be implemented, eliminating the trouble of manual deduplication.

洪涛

When you look at the source code, you only see the definition of the class, but you don’t explore it deeper. We know that in Java, there is single inheritance. You can only inherit one class, but you can implement multiple different interfaces.

 源码LinkedHashMap:
    public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> 
    源码HashMap:
    public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable 

之所以这样设计,我想有一下几个原因:
1.LinkedHashMap要保留Map这种数据结构的特性,因此它要实现Map所有的方法。
2.LinkedHashMap是对HashMap中无序问题提出的改进,因此,它继承了HashMap。
试想,如果你只继承了HashMap,而没有实现Map接口,那么是不是Map中的一些方法,LinkedHashMap可以不需要去实现的啊?那么LinkedHashMap保留Map这种数据结构的特性也就失去意义了。

仅供参考~~~
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!