【问题标题】:Is there a utility method for creating a list with specified size and contents?是否有创建具有指定大小和内容的列表的实用方法?
【发布时间】:2011-05-26 17:03:01
【问题描述】:
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 库是多余的。

【问题讨论】:

标签: java apache-commons utility utility-method


【解决方案1】:

Collections 实用程序类将帮助您:

list = Collections.nCopies(length,contents);

或者如果你想要一个可变列表:

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

【讨论】:

  • 谢谢,这正是我所缺少的!
【解决方案2】:

Google Guava 具有以下功能:

newArrayListWithExpectedSize(int estimatedSize)

和:

newArrayList(E... elements)

但你不能两者都做,如果有用的话可以提交一个补丁。更多信息在这里:

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

【讨论】:

  • 我不确定在上下文中这与使用 Arrays.asList() 有何不同。上面提到的 Collections.nCopies() 方法非常适合,所以我将使用它。
【解决方案3】:

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" );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    • 2021-10-19
    相关资源
    最近更新 更多