Documentation

The Java™ Tutorials
Trail: Collections

Lesson: Custom Collection Implementations课程:自定义集合实现

Many programmers will never need to implement their own Collections classes. 许多程序员永远不需要实现自己的Collection类。You can go pretty far using the implementations described in the preceding sections of this chapter. 使用本章前面几节中描述的实现,您可以走得更远。However, someday you might want to write your own implementation. 然而,有一天您可能会想编写自己的实现。It is fairly easy to do this with the aid of the abstract implementations provided by the Java platform. 借助Java平台提供的抽象实现,实现这一点相当容易。Before we discuss how to write an implementation, let's discuss why you might want to write one.在讨论如何编写实现之前,让我们先讨论一下为什么要编写一个实现。

Reasons to Write an Implementation编写实现的原因

The following list illustrates the sort of custom Collections you might want to implement. 下面的列表说明了您可能想要实现的自定义Collection的种类。It is not intended to be exhaustive:其目的并非详尽无遗:

How to Write a Custom Implementation如何编写自定义实现

Writing a custom implementation is surprisingly easy. 编写自定义实现非常简单。The Java Collections Framework provides abstract implementations designed expressly to facilitate custom implementations. Java 集合框架提供了抽象实现,这些抽象实现是专门为方便定制实现而设计的。We'll start with the following example of an implementation of Arrays.asList.我们将从以下Arrays.asList实现的示例开始。

public static <T> List<T> asList(T[] a) {
    return new MyArrayList<T>(a);
}

private static class MyArrayList<T> extends AbstractList<T> {

    private final T[] a;

    MyArrayList(T[] array) {
        a = array;
    }

    public T get(int index) {
        return a[index];
    }

    public T set(int index, T element) {
        T oldValue = a[index];
        a[index] = element;
        return oldValue;
    }

    public int size() {
        return a.length;
    }
}

Believe it or not, this is very close to the implementation that is contained in java.util.Arrays. 信不信由你,这与java.util.Arrays中包含的实现非常接近。It's that simple! 就这么简单!You provide a constructor and the get, set, and size methods, and AbstractList does all the rest. 您提供了一个构造函数以及getsetsize方法,而AbstractList完成了所有其余的工作。You get the ListIterator, bulk operations, search operations, hash code computation, comparison, and string representation for free.您可以免费获得ListIterator、批量操作、搜索操作、哈希代码计算、比较和字符串表示。

Suppose you want to make the implementation a bit faster. 假设您想让实现更快一点。The API documentation for abstract implementations describes precisely how each method is implemented, so you'll know which methods to override to get the performance you want. 抽象实现的API文档精确地描述了每个方法的实现方式,因此您将知道要覆盖哪些方法以获得所需的性能。The preceding implementation's performance is fine, but it can be improved a bit. 前面的实现的性能很好,但可以稍微改进一下。In particular, the toArray method iterates over the List, copying one element at a time. 特别是,toArray方法在List上迭代,一次复制一个元素。Given the internal representation, it's a lot faster and more sensible just to clone the array.考虑到内部表示,仅克隆阵列就更快、更合理。

public Object[] toArray() {
    return (Object[]) a.clone();
}

With the addition of this override and a few more like it, this implementation is exactly the one found in java.util.Arrays. 加上这个覆盖和其他一些类似的功能,这个实现就是java.util.Arrays中的实现。In the interest of full disclosure, it's a bit tougher to use the other abstract implementations because you will have to write your own iterator, but it's still not that difficult.为了充分公开,使用其他抽象实现有点困难,因为您必须编写自己的迭代器,但仍然没有那么困难。

The following list summarizes the abstract implementations:以下列表总结了抽象实现:

The process of writing a custom implementation follows:编写自定义实现的过程如下所示:

  1. Choose the appropriate abstract implementation class from the preceding list.从前面的列表中选择适当的抽象实现类。
  2. Provide implementations for all the abstract methods of the class. If your custom collection is to be modifiable, you will have to override one or more of the concrete methods as well. 为类的所有抽象方法提供实现。如果要修改自定义集合,还必须重写一个或多个具体方法。The API documentation for the abstract implementation class will tell you which methods to override.抽象实现类的API文档将告诉您要覆盖哪些方法。
  3. Test and, if necessary, debug the implementation. 测试并在必要时调试实现。You now have a working custom collection implementation.现在,您有了一个工作的自定义集合实现。
  4. If you are concerned about performance, read the API documentation of the abstract implementation class for all the methods whose implementations you're inheriting. 如果您关心性能,请阅读抽象实现类的API文档,了解您要继承其实现的所有方法。If any seem too slow, override them. 如果其中任何一个看起来太慢,请覆盖它们。If you override any methods, be sure to measure the performance of the method before and after the override. 如果重写任何方法,请确保在重写之前和之后测量该方法的性能。How much effort you put into tweaking performance should be a function of how much use the implementation will get and how critical to performance its use is. 您在调整性能方面投入了多少精力,应该取决于实现将得到多少使用,以及使用它对性能的重要性。(Often this step is best omitted.)(通常这一步最好省略。)

Previous page: Previous Lesson
Next page: Interoperability