ImmutableList不扩展List? [英] ImmutableList does not extend List?

查看:167
本文介绍了ImmutableList不扩展List?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我深入到 ImmutableList 的gs-collection源时,它不会扩展 java.util.List 。但是javadoc类提到了所有ImmutableList实现必须实现 java.util.List



实现 java.util.List 而不是 ImmutableList 本身来扩展 java.util

ImmutableList

extend 列表




When I dig into the gs-collection source for ImmutableList, it does not extends java.util.List. However the class javadoc mentioned that All ImmutableList implementations must implement the java.util.List.

Why must ask the implementation to implement java.util.List and not the ImmutableList itself to extend java.util.List?

解决方案

Why doesn't ImmutableList extend List?

ImmutableCollection doesn't extend java.util.Collection (and ImmutableList doesn't extend java.util.List) because Collection has mutating methods like add() and remove(). If immutable collections had these methods, they would always have to throw UnsupportedOperationException. For users of immutable collections, it would be strange to see add() and remove() in auto-complete choices as callable methods.

Why does the Javadoc impose a contract that all ImmutableList implementations also implement List?

It comes down to equality. An ImmutableList ought to equal a List, assuming both lists have the same contents in the same order. List.equals() imposes a Javadoc contract which states:

Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal.

What does it mean that "the specified object is also a list?" We can see in AbstractList.equals() that it means instanceof List.

public boolean equals(Object o) {
    if (o == this)
        return true;
    if (!(o instanceof List))
        return false;
    ...
}

So all ImmutableList implementations must also implement List for equals() to work in a symmetric way. The immutable collection factories already hide implementation details like the fact that an immutable list with a single element is implemented by an ImmutableSingletonList. It also winds up hiding the List interface.

Interop

A benefit of this design is that ImmutableList can be cast to List which is important for interop with existing APIs.

// Library method - cannot refactor the parameter type
public void printAll(List<?> list)
{
    for (Object each : list)
    {
        System.out.println(each);
    }
}

ImmutableList<Integer> immutableList = Lists.immutable.with(1, 2, 3);
List<Integer> castList = immutableList.castToList();
printAll(castList);
// also works
printAll((List<?>) immutableList);

// throws UnsupportedOperationException
castList.add(4);

Note: I am a developer on GS Collections.

这篇关于ImmutableList不扩展List?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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