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

sponsored links
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.

  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

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

  • Learning ruby on rails video tutorials and e-book download

    25, and are not large, fast download! http://www.railscasts.com/ Books, personal recommend Agile Web Development with Rails (Chinese version translated well, e-books is the first version 2) and Rails Recipes (print out bar, Value!), And ruby for rail ...

  • REST on Rails

    Series, the previous article said that Ruby on Rails is a sudden pop up a framework for the Ruby programming language to serve as a catalyst. With the continued success of the experience of Ruby, developers began to seek their Ruby applications and u ...

  • Ext JS FormPanel summary of the submission of data ....

    Returns the fields in this form as an object with key / value pairs as they would be submitted using a standard form submit. If multiple fields exist with the same name they are returned as an array. Parameters: * AsString: Boolean (optional) false t ...

  • An essential reference resource list of Java

    Since the Java platform since 1995 as a whole began to introduce programming community, and its development has gone far beyond the early Java experts and those who promote the idea of "applet ubiquitous" of that vision. In contrast, Java emerge

  • Javascript in the browser environment (seven) XMLHttpRequest

    XMLHttpRequest XMLHttpRequest is a function used to create a http request. XHR initial IE through ActiveX objects are realized. After the beginning of the various browsers support. Now AJAX is the popular XMLHttpRequest object to the adoption of the imple

  • Imitation Java type HashMap implementation of JavaScript

    Imitation Java type HashMap implementation of JavaScript

  • In the Linux platform to install and configure Ruby on Rails Detailed

    ruby on rails recommend the production environment is running Linux / FreeBSD / Unix, or Unix family of operating systems, using lighttpd + FCGI solution. The following will be my Linux operating system, lighttpd + FCGI, MySQL database as an example, comp

  • JAVA interview questions

    JAVA interview questions 1, object-oriented features of what has 1. Abstract 2. Inheritance 3. Packaging 4. Polymorphisms 2, String data types are the most basic right? Basic data types include byte, int, char, long, float, double, boolean and short. java

blog comments powered by Disqus
Recent Entries
Tag Cloud
Random Entries