KBD

Keith Devens .com

Tuesday, December 2, 2008 Flag waving
A Lisp programmer knows the value of everything, but the cost of nothing. – Alan Perlis
← Ned Batchelder: Object reference not set to an instance of an objectThe World's Ugliest Car, restored →

Daily link icon Tuesday, October 11, 2005

Arrays.asList()

Arrays.asList is a feature every Java developer should know about. It'll save you from writing code like:

List<Foo> foolist = new ArrayList<Foo>();
foolist.add(foo);
return foolist;

or maybe

if(map.containsKey(id)){
    map.get(id).add(foo);
}else{
    List<Foo> foolist = new ArrayList<Foo>();
    foolist.add(foo);
    map.put(id, foo);
}

and allow you to write code like:

return Arrays.asList(foo);

and

if(map.containsKey(id))
    map.get(id).add(foo);
else
    map.put(id, Arrays.asList(foo));

Update: I didn't notice that Arrays.asList returns a List that can't be added too. When you try to call add on the returned List, you'll get an UnsupportedOperationException in AbstractList.add. That seemed lame to me, but the List interface does say that add is an "optional operation". For the lists to be mutable, the above code snippets have to be changed to something like:

return new ArrayList<Foo>(Arrays.asList(foo));

and

if(map.containsKey(id))
    map.get(id).add(foo);
else
    map.put(id, new ArrayList<Foo>(Arrays.asList(foo)));

Update: Of course, the more pathalogical example of what Arrays.asList saves you from is:

List<Foo> foolist = new ArrayList<Foo>(fooarray.length);
for(int i=0,n=fooarray.length; i<n; i++){
    foolist.add(fooarray[i]);
}

or

List<Foo> foolist = new ArrayList<Foo>(fooarray.length);
for(Foo f : fooarray){
    foolist.add(f);
}

because that becomes just:

List<Foo> foolist = Arrays.asList(fooarray);
← Ned Batchelder: Object reference not set to an instance of an objectThe World's Ugliest Car, restored →

Comments XML gif

B. K. Oxley (binkley) (http://binkley.blogspot.com) wrote:

You might also chose to mention the Collections class with static methods such as addAll(...), the helpful public static members EMPTY_LIST, et al, and most on point for your code example, singletonList(T). Thus:

Arrays.asList(foo);

Becomes:

Collections.singletonList(foo);

Which to me seems to document better the intention of the code. However, the returned list is indeed a singleton: you cannot later modify it, so that may violate the contract of the surrounding method for the code fragment.

∴ B. K. Oxley (binkley) | 12-Oct-2005 7:48am est | http://binkley.blogspot.com | #8453

Madhusudhan Rao (http://jroller.com/page/madwho) wrote:

I usually have the following utility to create lists

public abstract class Utils {
    public static <T> List<T> list(T... elements) {
        final List<T> result = new ArrayList<T>();
        for (T element : elements) {
            result.add(element);
        }
        return result;
    }
}

Usage:

final List<String> coffees = Utils.list("mocha", latte");
∴ Madhusudhan Rao | 14-Oct-2005 1:25am est | http://jroller.com/page/madwho | #8457

Keith (http://keithdevens.com/) wrote:

Cool, thanks. I wonder how much more efficient that is, if any, than the above:

new ArrayList<Foo>(Arrays.asList(foo));

Also, may I recommend a small change:

final List<T> result = new ArrayList<T>(elements.length);

for obvious reasons.

Keith | 14-Oct-2005 1:52am est | http://keithdevens.com/ | #8458

Feel free to post a comment below. Please see my comment policy.

Formatting Rules (No HTML):

  • **bold**, *italic*, _underlined_, --strikeout--
  • "text"="url" creates a link, and URLs are auto-highlighted
  • Blockquote: Like e-mail, begin paragraph with > (greater-than sign)
  • Lists: begin paragraph with *,-, or + (unordered), or # (ordered)
  • Code block: ?!code:language=perl|php|sql|javascript|etc.{\n}...{\n}?!/code

:
(will be your IP address if blank)
: (optional)
(Will not be shown on site)

: (optional)
:

December 2008
SunMonTueWedThuFriSat
 123456
78910111213
14151617181920
21222324252627
28293031 



RSS feed RSS feed for Keith's Weblog
Atom feed Atom feed for Keith's Weblog
Weblog archive
Recent comments
  on 6 posts

Recent comments XML

new⇒Perl 6 1.0 in March?

Doh, my mistake. I'm aware of the​relation between Parrot and Rakudo​but I'...

Keith: Dec 2, 1:03am

Free image hosting sites

Well, TinyPic has this in its​FAQ:

> Images and videos is in​your accoun...

Keith: Dec 1, 1:13am

Join a NameValueCollection into a querystring in C#

Well with a lamba expression, this​is what I came up​with:

?!code:csharp...

Gustaf Lindqvist: Nov 30, 4:38pm

Why no generic OrderedDictionary?

Check​http://www.codeproject.com/KB/recip​es/GenericOrderedDictionary.aspx?d...

Gabrielk: Nov 27, 6:57am

WhatIsMyIP.com

http://www.thesysteminfo.com is​another good alternate to​whatismp.com... I...

Kripz: Nov 26, 8:51pm

Girls, please don't get breast implants

Actually I think it's sweet when a​man loves a woman whether she's big​or n...

218.186.12.228: Nov 26, 9:40am

Generated in about 0.263s.

(Used 8 db queries)

mobile phone