`
qqdwll
  • 浏览: 136722 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

<转载> 5 things you didn't know about ... the Java Collections API, Part 1

    博客分类:
  • Java
阅读更多
原本来自: http://www.ibm.com/developerworks/java/library/j-5things2.html

1. Collections trump arrays

Developers new to Java technology may not know that arrays were originally included in the language to head-off performance criticism from C++ developers back in the early 1990s. Well, we've come a long way since then, and the array's performance advantages generally come up short when weighed against those of the Java Collections libraries.

Dumping array contents into a string, for example, requires iterating through the array and concatenating the contents together into a String; whereas, the Collections implementations all have a viable toString() implementation.

Except for rare cases, it's good practice to convert any array that comes your way to a collection as quickly as possible. Which then begs the question, what's the easiest way to make the switch? As it turns out, the Java Collections API makes it easy, 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
        System.out.println(args);
       
        // Convert args to a List of String
        List<String> argList = Arrays.asList(args);
       
        // Print them out
        System.out.println(argList);
    }
}


Note that the returned List is unmodifiable, so attempts to add new elements to it will throw an UnsupportedOperationException.

And, because Arrays.asList() uses a varargs parameter for elements to add into the List, you can also use it to easily create Lists out of newed objects.


2. Iterating is inefficient

It's not uncommon to want to move the contents of one collection (particularly one that was manufactured out of an array) over into another collection or to remove a small collection of objects from a larger one.

You might be tempted to simply iterate through the collection and add or remove each element as it's found, but don't.

Iterating, in this case, has major disadvantages:

It would be inefficient to resize the collection with each add or remove.
There's a potential concurrency nightmare in acquiring a lock, doing the operation, and releasing the lock each time.
There's the race condition caused by other threads banging on your collection while the add or remove is taking place.
You can avoid all of these problems by using addAll or removeAll to pass in the collection containing the elements you want to add or remove.


3. For loop through any Iterable

The enhanced for loop, one of the great conveniences added to the Java language in Java 5, removed the last barrier to working with Java Collections.

Before, developers had to manually obtain an Iterator, use next() to obtain the object pointed to from the Iterator, and check to see if more objects were available via hasNext(). Post Java 5, we're free to use a for-loop variant that handles all of the above silently.

Actually, this enhancement works with any object that implements the Iterable interface, not just Collections.

Listing 2 shows one approach to making a list of children from a Person object available as an Iterator. Rather than handing out a reference to the internal List (which would enable callers outside the Person to add kids to your family — something most parents would find uncool), the Person type implements Iterable. This approach also enables the enhanced for loop to walk through the children.


Listing 2. Ehanced for loop: Show me your 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)
            children.add(child);
    }
    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)
        {
            System.out.println(kid.getFirstName());
        }
    }
}



Using Iterable has some obvious drawbacks when domain modeling, because only one such collection of objects can be so "implicitly" supported via the iterator() method. For cases where the child collection is obvious and apparent, however, Iterable makes programming against the domain type much easier and more obvious.


4. Classic and custom algorithms

Have you ever wanted to walk a Collection, but in reverse? That's where a classic Java Collections algorithm comes in handy.

The children of Person in Listing 2 above, are listed in the order that they were passed in; but, now you want to list them in the reverse order. While you could write another for loop to insert each object into a new ArrayList in the opposite order, the coding would grow tedious after the third or fourth time.

That's where the underused algorithm in Listing 3 comes in:


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
        Collections.reverse(kids);
        // Display it
        System.out.println(kids);
    }
}


The Collections class has a number of these "algorithms," static methods that are implemented to take Collections as parameters and provide implementation-independent behavior on the collection as a whole.

What's more, the algorithms present on the Collections class certainly aren't the final word in great API design — I prefer methods that don't modify the contents (of the Collection passed in) directly, for example. So it's a good thing you can write custom algorithms of your own, like the one shown in Listing 4:


Listing 4. ReverseIterator made simpler

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


5. Extend the Collections API

The customized algorithm above illustrates a final point about the Java Collections API: that it was always intended to be extended and morphed to suit developers' specific purposes.

So, for example, say you needed the list of children in the Person class to always be sorted by age. While you could write code to sort the children over and over again (using the Collections.sort method, perhaps), it would be far better to have a Collection class that sorted it for you.

In fact, you might not even care about preserving the order in which the objects were inserted into the Collection (which is the principal rationale for a List). You might just want to keep them in a sorted order.

No Collection class within java.util fulfills these requirements, but it's trivial to write one. All you need to do is create an interface that describes the abstract behavior the Collection should provide. In the case of a SortedCollection, the intent is entirely behavioral.


Listing 5. SortedCollection

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



It's almost anticlimactic to write an implementation of this new interface:


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;
        sortThis();
    }

    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 quick-and-dirty implementation, written with no optimizations in mind, could obviously stand some refactoring. But the point is, the Java Collections API was never intended to be the final word in all things collection-related. It both needs and encourages extensions.

Certainly, some extensions will be of the "heavy-duty" variety, such as those introduced in java.util.concurrent. But others will be as simple as writing a custom algorithm or a simple extension to an existing Collection class.

Extending the Java Collections API might seem overwhelming, but once you start doing it, you'll find it's nowhere near as hard as you thought.


In conclusion

Like Java Serialization, the Java Collections API is full of unexplored nooks and crannies — which is why we're not done with this subject. The next article in the 5 things series will give you five more ways to do even more with the Java Collections API.
分享到:
评论

相关推荐

    C#重要知识之——泛型列表List例子

    `List&lt;T&gt;`是.NET框架中的一个类,位于`System.Collections.Generic`命名空间下。这里的`T`代表一个类型参数,允许我们创建一个可以存储特定类型对象的列表。例如,我们可以创建一个存储整数的`List&lt;int&gt;`或存储字符...

    Apache Commons 所有包最新版本 含SRC (4/7)

    chain-1.2-bin.zip&lt;br&gt;commons-chain-1.2-src.zip&lt;br&gt;commons-cli-1.1-src.zip&lt;br&gt;commons-cli-1.1.zip&lt;br&gt;commons-codec-1.3-src.zip&lt;br&gt;commons-codec-1.3.zip&lt;br&gt;commons-collections-3.2.1-bin.zip&lt;br&gt;commons-...

    java实现poi 在线预览,excel,word直接在页面显示,附带文件上传,多文件上传

    &lt;artifactId&gt;commons-collections4&lt;/artifactId&gt; &lt;version&gt;4.1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.poi&lt;/groupId&gt; &lt;artifactId&gt;poi&lt;/artifactId&gt; &lt;version&gt;3.17&lt;/version&gt; &lt;/...

    spring-hibernate-dwr实例

    spring-hibernate-dwr做的AJAX操作CRUD实例&lt;br&gt;环境:myeclipse6.0+jdk1.6&lt;br&gt;所需lib列表,请自行加入&lt;br&gt;mysql-connector-java-3.1.7-bin.jar&lt;br&gt;antlr-2.7.6rc1.jar&lt;br&gt;asm-attrs.jar&lt;br&gt;cglib-2.1.3.jar&lt;br&gt;...

    spring+struts+hibernate+dwr+jstl做的实例

    2.7.6rc1.jar&lt;br&gt;asm.jar&lt;br&gt;asm-attrs.jar&lt;br&gt;cglib-2.1.3.jar&lt;br&gt;commons-collections-2.1.1.jar&lt;br&gt;commons-logging-1.0.4.jar&lt;br&gt;dom4j-1.6.1.jar&lt;br&gt;ehcache-1.1.jar&lt;br&gt;hibernate3.jar&lt;br&gt;jaas.jar&lt;br&gt;jaxen-...

    Visual C++ 编程资源大全(英文源码 ATL)

    update_wtl.zip&lt;br&gt;Notes on updating your WTL installation(2KB)&lt;END&gt;&lt;br&gt;27,sidebarmenu.zip&lt;br&gt;An article about changing the look of WTL icon menu(85KB)&lt;END&gt;&lt;br&gt;28,customdraw.zip&lt;br&gt;How to use WTL to ...

    Visual C++ 编程资源大全(英文源码 网络)

    31.zip&lt;br&gt;Novell Netware Send&lt;br&gt;Netware网络间的信息发送(4KB)&lt;END&gt;&lt;br&gt;109,32.zip&lt;br&gt;Winsock API Wrapper Classes&lt;br&gt;Winsock API包装类(5KB)&lt;END&gt;&lt;br&gt;110,33.zip&lt;br&gt;ISAPI authentication filter&lt;br&gt;ISAPI身份...

    Visual.Studio.Tools.for.Office.Using.C.Sharp.with.Excel.Word.Outlook.and.InfoPath.Sep.2005.part2

    &lt;br&gt; Copyright &lt;br&gt; Praise for Visual Studio Tools for Office &lt;br&gt; Microsoft .NET Development Series &lt;br&gt; Titles in the Series &lt;br&gt; About the Authors &lt;br&gt; Foreword &lt;br&gt; Preface &lt;br&gt; Acknowledgments ...

    JSF与Shale开发用包

    其中包含:shale-core.jar&lt;br&gt;commons-beanutils.jar&lt;br&gt;commons-chain.jar&lt;br&gt;commons-codec.jar&lt;br&gt;commons-collections.jar&lt;br&gt;commons-digester.jar&lt;br&gt;commons-el.jar&lt;br&gt;commons-fileupload.jar&lt;br&gt;commons-...

    C# xmlToList xml转换成对象

    public static List&lt;T&gt; XmlToList&lt;T&gt;(string xmlFilePath) where T : new() { var list = new List&lt;T&gt;(); XmlDocument doc = new XmlDocument(); doc.Load(xmlFilePath); using (XmlNodeReader reader = new ...

    C#+List+GridControl实现主从表嵌套

    `List&lt;T&gt;`是.NET Framework中`System.Collections.Generic`命名空间下的一个泛型集合类,它实现了`IList&lt;T&gt;`、`ICollection&lt;T&gt;`和`IEnumerable&lt;T&gt;`接口。`List&lt;T&gt;`是用于存储强类型对象的动态数组,允许快速的插入和...

    关于 Java Collections API 您不知道的 5 件事

    ### 关于 Java Collections API 您不知道的 5 件事 #### 1. Collections 比数组更好 在 Java 的早期阶段,为了回应 C++ 开发者对于性能的批评,Java 引入了数组这一概念。然而,随着时间的发展,Java 的 ...

    Visual.Studio.Tools.for.Office.Using.C.Sharp.with.Excel.Word.Outlook.and.InfoPath.Sep.2005

    &lt;br&gt; Copyright &lt;br&gt; Praise for Visual Studio Tools for Office &lt;br&gt; Microsoft .NET Development Series &lt;br&gt; Titles in the Series &lt;br&gt; About the Authors &lt;br&gt; Foreword &lt;br&gt; Preface &lt;br&gt; Acknowledgments ...

    hibernate 教程

    目录&lt;br&gt;&lt;br&gt;前言&lt;br&gt;1. 翻译说明&lt;br&gt;1. 在Tomcat中快速上手&lt;br&gt;1.1. 开始Hibernate之旅&lt;br&gt;1.2. 第一个可持久化类&lt;br&gt;1.3. 映射cat&lt;br&gt;1.4. 与猫同乐&lt;br&gt;1.5. 结语&lt;br&gt;2. 体系结构&lt;br&gt;2.1. 总览&lt;br&gt;2.2. JMX集成&lt;br...

    hibernate

    目录&lt;br&gt;&lt;br&gt;前言&lt;br&gt;1. 翻译说明&lt;br&gt;1. 在Tomcat中快速上手&lt;br&gt;1.1. 开始Hibernate之旅&lt;br&gt;1.2. 第一个可持久化类&lt;br&gt;1.3. 映射cat&lt;br&gt;1.4. 与猫同乐&lt;br&gt;1.5. 结语&lt;br&gt;2. 体系结构&lt;br&gt;2.1. 总览&lt;br&gt;2.2. JMX集成&lt;br...

    Apress - Pro Java Programming, 2nd Edition.pdf

    Pro Java Programming,&lt;br&gt;Second Edition&lt;br&gt;BRETT SPELL&lt;br&gt;&lt;br&gt;■CHAPTER 1 Going Inside Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1&lt;br&gt;■CHAPTER 2...

    Addison.Wesley.The.Java.Programming.Language.4th.Edition.Aug.2005.chm

    java.util, java.io) as implemented in the J2SE™ Development Kit 5.0 (more commonly known as JDK 5.0, or in the older nomenclature JDK 1.5.0).&lt;br&gt;&lt;br&gt;If you have already read the third edition of ...

    Java基础23(Excel文件解析)

    5. commons-collections4-4.4.jar:Apache Commons Collections库,提供了对Java集合框架的增强功能,可能在处理数据时被用到。 6. fastjson-1.2.62.jar:Fastjson是阿里巴巴的一个高性能的JSON库,可以用于JSON和...

    c#数据库操作的3种典型用法

    &lt;br&gt;using System.Collections.Generic;&lt;br&gt;using System.Text;&lt;br&gt;using System.Data;&lt;br&gt;using System.Data.SqlClient;&lt;br&gt; &lt;br&gt;namespace DatabaseOperate&lt;br&gt;{&lt;br&gt; class SqlOperateInfo&lt;br&gt; {&lt;br&gt; //Suppose ...

    Apress.Pro.LINQ.Language.Integrated.Query.in.C.Sharp.2008.Nov.2007.eBook-BBL

    英文版&lt;br&gt;===================================================&lt;br&gt; Pro LINQ: Language Integrated Query in C# 2008 (c) by Apress&lt;br&gt;&lt;br&gt; The type of the release is: eBook&lt;br&gt; In the PDF format with ISBN...

Global site tag (gtag.js) - Google Analytics