是否有一个实用方法来创建具有指定大小和内容的列表?
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 库来说通常是多余的。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Collections
实用程序类将为您提供帮助:或者如果您想要一个可变列表:
The
Collections
utility class will help you:or if you want a mutable list:
Google Guava 有以下功能:
和:
但你不能两者兼而有之,如果有用的话,也许可以提交一个补丁。更多信息请参见:
http://guava -libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Lists.html
Google Guava has the following:
and:
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
怎么样
java.util.Arrays.asList
?您可以将内容作为 var-arg< 传递/a>:
请注意,您也可以传入一个数组:
但它是由数组“支持”的,因为更改数组的内容将反映在列表中:
How about
java.util.Arrays.asList
?You can just pass in the contents as a var-arg:
Mind you, you can pass in an array as well:
but it is "backed" by the array in that changing the contents of the array will be reflected in the list: