4
public static <T> List<T> repeat(T contents, int length) {
    List<T> list = new ArrayList<T>();
    for (int i = 0; i < length; i++) {
        list.add(contents);
    }
    return list;
}

This is a utility method in our proprietary commons libraries. It's useful for creating lists. For example, I might want a list of 68 question marks for generating a large SQL query. This lets you do that in one line of code, instead of four lines of code.

Is there a utility class somewhere in java/apache-commons which already does this? I browsed ListUtils, CollectionUtils, Arrays, Collections, pretty much everything I could think of but I can't find it anywhere. I don't like keeping generic utility methods in my code, if possible, since they're usually redundant with apache libraries.

Sled
  • 18,541
  • 27
  • 119
  • 168
piepera
  • 2,033
  • 1
  • 20
  • 21
  • Will Arrays.fill work for you ? http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#fill%28java.lang.Object[],%20java.lang.Object%29 – Santosh Gokak May 26 '11 at 17:12
  • Arrays.fill would be a little clumsy here, it fits a slightly different role. – piepera May 26 '11 at 21:17

3 Answers3

16

The Collections utility class will help you:

list = Collections.nCopies(length,contents);

or if you want a mutable list:

list = new ArrayList<T>(Collections.nCopies(length,contents));
           // or whatever List implementation you want.
ratchet freak
  • 47,288
  • 5
  • 68
  • 106
1

Google Guava has the following:

newArrayListWithExpectedSize(int estimatedSize)

and:

newArrayList(E... elements)

but you can't do both, maybe submit a patch if it's going to be useful. More info here:

http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Lists.html

Jonathan Holloway
  • 62,090
  • 32
  • 125
  • 150
  • I'm not sure how different that is, in context, from using Arrays.asList(). The Collections.nCopies() method mentioned above is a perfect fit, so I'll use that. – piepera May 26 '11 at 21:19
0

How about java.util.Arrays.asList ?

You can just pass in the contents as a var-arg:

List<String> planets = Arrays.asList( "Mercury", "Venus", "Earth", "Mars" );

Mind you, you can pass in an array as well:

String[] ps = new String[]{ "Mercury", "Venus", "Earth", "Mars" };
List<String> planets = Arrays.asList( ps );

but it is "backed" by the array in that changing the contents of the array will be reflected in the list:

String[] ps = new String[]{ "Mercury", "Venus", "Earth", "Mars" };
List<String> planets = Arrays.asList( ps );
ps[3] = "Terra";
assert planets.get(3).equals( "Terra" );
Sled
  • 18,541
  • 27
  • 119
  • 168