问题
Say, I want to create a list quickly which contains 1000 elements. What is the best way to accomplish this?
回答1:
You can use Collections.nCopies.
Note however that the list returned is immutable. In fact, the docs says "it the newly allocated data object is tiny (it contains a single reference to the data object)".
If you need a mutable list, you would do something like
List<String> hellos = new ArrayList<String>(Collections.nCopies(1000, "Hello"));
If you want 1000 distinct objects, you can use
List<YourObject> objects = Stream.generate(YourObject::new)
.limit(1000)
.collect(Collectors.toList());
Again, there is not guarantees about the capabilities of the resulting list implementation. If you need, say an ArrayList
, you would do
...
.collect(ArrayList::new);
回答2:
Fastest : int[] myList = new int[1000]
will contain 1000 elements equal to zero. But I'm sure it doesn't suit your needs. Tell us more of what you need and I might be able to help :)
来源:https://stackoverflow.com/questions/8267348/how-to-create-a-list-with-specific-size-of-elements