是否有实用程序方法来创建具有指定大小和内容的列表?

|
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;
}
这是我们专有公共库中的一种实用方法。这对于创建列表很有用。例如,我可能想要一个68个问号的列表来生成一个大型SQL查询。这样一来,您只需一行代码,而不是四行代码。 java / apache-commons中的某个地方已经有实用程序类了吗?我浏览了ListUtils,CollectionUtils,Arrays,Collections,几乎所有我能想到的东西,但在任何地方都找不到。如果可能的话,我不喜欢将通用实用程序方法保留在我的代码中,因为它们通常对apache库是多余的。     
已邀请:
Collections
实用程序类将帮助您:
list = Collections.nCopies(length,contents);
或者,如果您想要一个可变的列表:
list = new ArrayList<T>(Collections.nCopies(length,contents));
           // or whatever List implementation you want.
    
Google Guava具有以下功能:
newArrayListWithExpectedSize(int estimatedSize)
和:
newArrayList(E... elements)
但您不能两者都做,如果有用的话,也许可以提交补丁。更多信息在这里: http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Lists.html     
java.util.Arrays.asList
怎么样? 您可以将内容作为var-arg传递:
List<String> planets = Arrays.asList( \"Mercury\", \"Venus\", \"Earth\", \"Mars\" );
请注意,您也可以传入数组:
String[] ps = new String[]{ \"Mercury\", \"Venus\", \"Earth\", \"Mars\" };
List<String> planets = Arrays.asList( ps );
但是它受到数组的“支持”,因为更改数组的内容将反映在列表中:
String[] ps = new String[]{ \"Mercury\", \"Venus\", \"Earth\", \"Mars\" };
List<String> planets = Arrays.asList( ps );
ps[3] = \"Terra\";
assert planets.get(3).equals( \"Terra\" );
    

要回复问题请先登录注册