[Reprinted] on the Java Collections API 5 things you do not know, Part 1

Original: http://www.ibm.com/developerworks/cn/java/j-5things2.html

On the Java Collections API 5 things you do not know, Part 1

Customization and extension Java Collections

Ted Neward , competent, Neward & Associates

[Reprinted] on the Java Collections API 5 things you do not know, Part 1

Ted Neward is Neward & Associates director, responsible for Java,. NET, XML services, and other platforms, advice, guidance, training and promotion. He now lives near Seattle, Washington.

Description: Java ™ Collections API is far more than just an array of alternatives, although such use is not bad for a start. Ted Neward provides information on the use of Collections to do more of the five techniques, including custom and extend the basis of Java Collections API.

Release Date: May 24, 2010
Other language versions: English

For many Java developers, Java Collections API is a standard Java array and all of its shortcomings as a much-needed alternative. Collections will be linked together primarily ArrayList not wrong in itself, but for those exploring the spirit of people, this is just the tip of the iceberg Collections.

About this series

You understand that your Java programming? In fact, most programmers for the Java platform are to taste was only just learning enough to complete the task at hand knowledge of it. In this series of, Ted Neward Java platform dig the core functions, reveals some little-known facts to help you solve the most difficult programming challenges.

Although Map (and its common implementation HashMap) is ideal name - value pairs or key - value pairs, but there is no reason to limit ourselves to these familiar tools. You can use the appropriate API, or even appropriate Collection to correct many error-prone code.

This is a 5 issue series in the second article is devoted to the Collections of the seven articles in the first article, why spend so much devoted Collections, because they set in the Java programming is so important. First of all, to do everything I will discuss the fastest (but perhaps not the most common) way, for example, Array contents transferred to List. Then we look at some of what fewer people know, for example, write custom classes and extend Collections Java Collections API.

1. Collections better than the array

New to Java technology developers may not know, Java language was originally included an array, in response to the early 90s C + + developers for performance criticism. Since then, we have come a long way, now, compared with the Java Collections library, the array no longer have performance advantages.

For example, to dump the contents of the array to a string, the entire array needs iteration, then the content connection into a String; and Collections of the realization of a usable toString() have achieved.

Few exceptions, good practice will meet as soon as possible of any array into a collection. So the question arises, to complete the conversion of the most easy way is what? Proved, Java Collections API to make this transition easier, as shown in Listing 1:

Listing 1. ArrayToList

import java.util.*;

public class ArrayToList
    public static void main(String[] args)
        // This gives us nothing good

        // Convert args to a List of String
        List<String> argList = Arrays.asList(args);

        // Print them out

Note that the returned List is not modified, so if one tries to add a new element to throw a UnsupportedOperationException.

And, because Arrays.asList() use varargs parameters that add to the List elements, so it can use it easily to the new object is created new List.

Back to top

2. Less efficient iteration

A set (in particular, transformed by the collection of an array) to another set of the contents, or from a large set of objects to remove a small set of objects, these things are not uncommon.

You may want to iterate the collection, and then add or remove elements to find the element, but not to do so.

In this case, iterative great disadvantages:

  • After each add or remove elements to re-adjust the set would be very inefficient.
  • Each access to the lock, perform the operation and release the lock of the process, all potential concurrency difficulties.
  • When you add or remove elements, access to the collection of other threads will cause competition.

By using addAll or removeAll, incoming contains elements of its collection to add or remove as a parameter, to avoid all these problems.

Back to top

3. With any Iterable for looping through

Adding Java Java 5 language features one of the greatest convenience, enhanced for loop, eliminating the use of Java set the final hurdle.

Previously, developers must manually get a Iterator, use next() get Iterator point of the object, and through hasNext() check if there are more available objects. Java 5 from the start, we are free to use for loop variants, which can handle all of the above work in the background.

In fact, this increase applies to any object to achieve Iterable interface, not just Collections.

Listing 2 shows the object through Iterator children Person list provided a way. This is not to provide internal List a reference (which makes Person caller outside the home increased for children - and most parents do not hope so), Person type to achieve Iterable. This approach also allows for loop to traverse all children.

Listing 2. Enhanced for loop: display children

// Person.java
import java.util.*;

public class Person
    implements Iterable<Person>
    public Person(String fn, String ln, int a, Person... kids)
        this.firstName = fn; this.lastName = ln; this.age = a;
        for (Person child : kids)
    public String getFirstName() { return this.firstName; }
    public String getLastName() { return this.lastName; }
    public int getAge() { return this.age; }

    public Iterator<Person> iterator() { return children.iterator(); }

    public void setFirstName(String value) { this.firstName = value; }
    public void setLastName(String value) { this.lastName = value; }
    public void setAge(int value) { this.age = value; }

    public String toString() {
        return "[Person: " +
            "firstName=" + firstName + " " +
            "lastName=" + lastName + " " +
            "age=" + age + "]";

    private String firstName;
    private String lastName;
    private int age;
    private List<Person> children = new ArrayList<Person>();

// App.java
public class App
    public static void main(String[] args)
        Person ted = new Person("Ted", "Neward", 39,
            new Person("Michael", "Neward", 16),
            new Person("Matthew", "Neward", 10));

        // Iterate over the kids
        for (Person kid : ted)

In the time domain modeling, use Iterable some obvious flaws, because the method can only be so by iterator() "sensitive" to support a collection of like objects. However, more obvious if the child set, Iterable can make for a domain type of programming easier and more intuitive.

Back to top

4. Classic algorithms and custom algorithms

Have you ever thought to reverse traverse a Collection? In this case, using the classic Java Collections algorithm is very convenient.

In the above list of 2 in, Person child is in accordance with the incoming order of; but now they are listed in reverse order. Although you can write another for loop in reverse order of each object into a new ArrayList in, but after 3,4 times to repeat this, it will feel a lot of trouble.

In this case, the algorithm in Listing 3, there will be a battlefield:

Listing 3. ReverseIterator

public class ReverseIterator
    public static void main(String[] args)
        Person ted = new Person("Ted", "Neward", 39,
            new Person("Michael", "Neward", 16),
            new Person("Matthew", "Neward", 10));

        // Make a copy of the List
        List<Person> kids = new ArrayList<Person>(ted.getChildren());
        // Reverse it
        // Display it

Collections class has a lot of this "algorithm", which are implemented as static methods to Collections as a parameter, independent on the realization of acts against the entire collection.

And, because great API design, we do not completely based on the algorithm provided Collections class - for example, I like not directly modify the (incoming Collection's) content. So, you can write custom algorithm is a great thing, for example, Listing 4 is one such example:

Listing 4. ReverseIterator make things easier

class MyCollections
    public static <T> List<T> reverse(List<T> src)
        List<T> results = new ArrayList<T>(src);
        return results;

Back to top

5. Extension Collections API

Custom algorithm explained above on the Java Collections API to a final point: it is always appropriate to be extended and modified to meet the developer's specific purpose.

For example, suppose you need to Person class kids to sort by age. Although you can write code to sort the children over and over again (perhaps using Collections.sort method), but through a Collection class to automatically sort to be much better.

In fact, you may not even care about whether the order will be fixed for each object into Collection (this is the basic principle of List). You may just want them to press a certain order.

java.util not Collection class to meet these needs, but the preparation of such a class is simple. Simply create an interface, use it to describe the abstract behavior Collection should provide. For SortedCollection, its role is completely behavioral.

Listing 5. SortedCollection

public interface SortedCollection<E> extends Collection<E>
    public Comparator<E> getComparator();
    public void setComparator(Comparator<E> comp);

The preparation of this new implementation of the interface is simply not worth mentioning:

Listing 6. ArraySortedCollection

import java.util.*;

public class ArraySortedCollection<E>
    implements SortedCollection<E>, Iterable<E>
    private Comparator<E> comparator;
    private ArrayList<E> list;

    public ArraySortedCollection(Comparator<E> c)
        this.list = new ArrayList<E>();
        this.comparator = c;
    public ArraySortedCollection(Collection<? extends E> src, Comparator<E> c)
        this.list = new ArrayList<E>(src);
        this.comparator = c;

    public Comparator<E> getComparator() { return comparator; }
    public void setComparator(Comparator<E> cmp) { comparator = cmp; sortThis(); }

    public boolean add(E e)
    { boolean r = list.add(e); sortThis(); return r; }
    public boolean addAll(Collection<? extends E> ec)
    { boolean r = list.addAll(ec); sortThis(); return r; }
    public boolean remove(Object o)
    { boolean r = list.remove(o); sortThis(); return r; }
    public boolean removeAll(Collection<?> c)
    { boolean r = list.removeAll(c); sortThis(); return r; }
    public boolean retainAll(Collection<?> ec)
    { boolean r = list.retainAll(ec); sortThis(); return r; }

    public void clear() { list.clear(); }
    public boolean contains(Object o) { return list.contains(o); }
    public boolean containsAll(Collection <?> c) { return list.containsAll(c); }
    public boolean isEmpty() { return list.isEmpty(); }
    public Iterator<E> iterator() { return list.iterator(); }
    public int size() { return list.size(); }
    public Object[] toArray() { return list.toArray(); }
    public <T> T[] toArray(T[] a) { return list.toArray(a); }

    public boolean equals(Object o)
        if (o == this)
            return true;

        if (o instanceof ArraySortedCollection)
            ArraySortedCollection<E> rhs = (ArraySortedCollection<E>)o;
            return this.list.equals(rhs.list);

        return false;
    public int hashCode()
        return list.hashCode();
    public String toString()
        return list.toString();

    private void sortThis()
        Collections.sort(list, comparator);

This realization is very simple, does not consider the optimum time of writing, a clear need for reconstruction. But the key is the Java Collections API was never intended anything associated with the collection will die. It always needs to expand, while also encouraging expansion.

Of course, some more complex extensions, such as the introduction of java.util.concurrent extension. But others are very simple, just write a custom algorithm, or have a simple extension of Collection class.

Expand Java Collections API looks very difficult, but once started, you will find far less difficult than imagined.

Back to top


And as Java Serialization, Java Collections API there are many corners to wait for someone to explore - is why we do not yet ready to end this topic. In the five case series in the next article, will be able to see with the Java Collections API to do more of the five kinds of new ways.

<! - CMA ID: 491184 -> <! - Site ID: 10 -> <! - XSLT stylesheet used to transform this file: dw-article-6.0-beta.xsl ->

Back to top


Description Name Size Download method
This sample code j-5things2-src.zip 10KB HTTP

Information on the download method

Reference material



About the author

[Reprinted] on the Java Collections API 5 things you do not know, Part 1

Ted Neward is Neward & Associates director, responsible for Java,. NET, XML services, and other platforms, advice, guidance, training and promotion. He now lives near Seattle, Washington.


分类:Java 时间:2010-06-16 人气:194
blog comments powered by Disqus


  • Service Strategy: Understanding Service traps - to implement the Java platform should pay attention to matters of common errors 2010-09-25

    Keywords: mark richards java Affairs Original: http://www.ibm.com/developerworks/cn/java/j-ts1.html Transaction goal should be to achieve a high degree of data integrity and consistency. This article is for the Java platform to develop effective stra

  • Influence far beyond imagination Java - Why Java platform to be adopted 2009-09-17

    Types of development projects from the perspective of the java platform is based on B / S structure of the system, in the direction of the competition is fierce, there is this focus on the LAMP (Linux + Apache + Mysql + Php); also just the rise of Ra

  • JAVA platform for Chinese encoding (Upper) 2010-04-01

    Recently prepared within the project team to prepare a Java platform for the discussion of Chinese encoding problem, this is the first part of the outline, the second part of being prepared. . . . 1 Unicode and other 1.1 Code Origin Each country (or

  • java中的key接口解析 2014-12-05

    这篇文章主要介绍了java中的key接口,有需要的朋友可以参考一下 该接口实现了序列化,声明为 public interface Key extends Serializable Key 是所有密钥的顶层接口.它定义了供所有密钥对象共享的功能.所有的密钥都具有三个特征: ①.算法 这是该密钥的密钥算法.密钥算法通常是加密或不对称操作算法(如 DSA 或 RSA),它们将和那些算法及相关的算法(例如 MD5 和 RSA,SHA-1 和 RSA.Raw DSA 等等)一起使用.用 getAlgori

  • C language with dynamic array (similar to java in Arraylist) 2010-12-28

    / * * C language with dynamic array (similar to java in Arraylist) * / # Include <stdio.h> # Include <stdlib.h> typedef struct str { / / Save pointer to an array of elements int * a; / / Current number of elements int index; / / Array of eleme

  • How to access the open-source Java platform for cloud storage? 2010-12-01

    Although the term cloud computing is not new (Amazon in 2006, began offering its cloud services), but since 2008 it started to really become a popular term, this period, Google and Amazon cloud service gradually gained public attention. Google's App

  • java platform by jacob on excel, word for printing and other operations 2009-05-05

    Because the demand for projects, requires the ability to at a scheduled time automatically print a specific report. Statements primarily in the form excel. If it is c + + or c # what is simply a piece of cake. Unfortunately, despite their java implem

  • java Map 一个key其实可以保存多个value 2015-01-24

    我们平时使用的Map,都是只能在Map中保存一个相同的Key,我们后面保存的相同的key都会将原来的key的值覆盖掉,如下面的例子. [java] view plaincopyprint? package test62; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; public class test { /** * @param args * @author 王新 */ public st

  • In the java platform, the use of CKeditor image / file upload feature 2009-04-09

    It is a problem for a long time, in the CKeditor officials have not found the information online, we have only asp.net and php, so here want to help to write an example to everyone. Principle parts: In CKeditor configuration as official online said,

  • Current and upcoming Java platform open cloud 2011-05-03

    Java App Engine ( http://code.google.com/appengine/ ) BitNami Cloud ( http://bitnami.org/cloud ) CloudBees ( http://www.cloudbees.com/ ) Microsoft Azure ( http://www.microsoft.com/windowsazure/ ) Makara ( http://www.makara.com/ ) - Developer preview

iOS 开发

Android 开发

Python 开发



PHP 开发

Ruby 开发






Javascript 开发

.NET 开发



Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 闽ICP备15018612号

processed in 0.347 (s). 10 q(s)