使用连续的整数范围填充List [英] Populating a List with a contiguous range of integers
问题描述
我想要一个包含1到500范围内整数的列表。是否有某种方法可以使用Guava(或只是普通Java)创建此列表,而无需遍历范围并单独添加值在我自己的代码中?
I'd like to have a list which contains the integers in the range 1 to 500. Is there some way to create this list using Guava (or just plain Java) without having to loop through the range and add the values individually within my own code?
解决方法如下(在这里发布,因为一些答案给出了正确的答案)信息但没有一个给出完整的解决方案):
The solution is as follows (posted here as some answers gave the correct information but none of them gave the complete solution):
ContiguousSet.create(Range.closed(1, 500), DiscreteDomain.integers()).asList()
结果类型为 ImmutableList<整数>
推荐答案
使用Guava,您可以使用 Range
: http://docs.guava -libraries.googlecode.com/git/javadoc/com/google/common/collect/Range.html
Using Guava, you can resort to a Range
: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Range.html
当然,仍会有循环你的代码,但为了简单起见,它们可能会隐藏在代码中。
Of course, there will still be loops in your code, but they just might be hidden from the code for simplicity sake.
例如:
Range<Integer> yourValues = Range.closed(1, 500);
检查http://code.google.com/p/guava-libraries/wiki/RangesExplained 了解更多示例。
Keep请记住,如果你做需要最终迭代 Range
,你不能直接这样做,只能通过使用 DiscreteDomains .integers()
。
Keep in mind that if you do need to eventually iterate over the Range
, you cannot do so directly, only through using DiscreteDomains.integers()
.
这篇关于使用连续的整数范围填充List的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!