Is there a way to create a list of tools with the specified size and content?

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 useful method in our own community libraries. This is useful for creating lists. For example, I might need a list of the 68 question marks to generate a large SQL-query. This allows you to do it in one line of code instead of four lines of code.

Is there a utility class somewhere in the java / apache-commons, which already does this? I looked ListUtils, CollectionUtils, Arrays, Collections, almost everything you could think of, but I can not find it anywhere. I do not like to keep the general utility methods in my code, if possible, as they are usually redundant with apache libraries.

+4
source share
3 answers

Utility class Collections can help you:

 list = Collections.nCopies(length,contents); 

or if you want a non-permanent list:

 list = new ArrayList<T>(Collections.nCopies(length,contents)); // or whatever List implementation you want. Collections.nCopies (length, contents)); list = new ArrayList<T>(Collections.nCopies(length,contents)); // or whatever List implementation you want. 
+15
source

Google Guava is as follows:

 newArrayListWithExpectedSize(int estimatedSize) 

and

 newArrayList(E... elements) 

but you can not get around, both may submit a patch if it will be useful. More details here:

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

+1
source

How about java.util.Arrays.asList ?

You can simply transfer the contents as var-the arg :

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

Keep in mind that you can also pass an array:

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

but it is "supported" by the array in that the change in 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" ); ] { "Mercury", "Venus", "Earth", "Mars"}; String[] ps = new String[]{ "Mercury", "Venus", "Earth", "Mars" }; List<String> planets = Arrays.asList( ps ); ps[3] = "Terra"; assert planets.get(3).equals( "Terra" ); ps); String[] ps = new String[]{ "Mercury", "Venus", "Earth", "Mars" }; List<String> planets = Arrays.asList( ps ); ps[3] = "Terra"; assert planets.get(3).equals( "Terra" ); 
0
source

All Articles