I want to add multiple BigInteger values to an ArrayList. All I have found is examples that repeatedly add single values, each expressed on their own line of code. I’m looking for something like
ArrayList<BigInteger> array = {bigInt1, bigInt2, bigInt3};
and instead it’s:
ArrayList<BigInteger> array = new ArrayList<BigInteger>();
array.add(bigInt1);
array.add(bigInt2);
array.add(bigInt3);
Can it be done, without adding one element/line or using a for loop?
I’m not really sure what you’re after. You have four alternatives:
1. Add items individually
Instantiate a concrete
Listtype and then calladd()for each item:2. Subclass a concrete
Listtype (double brace initialization)Some might suggest double brace initialization like this:
I recommend not doing this. What you’re actually doing here is subclassing
ArrayList, which (imho) is not a good idea. That sort of thing can breakComparators,equals()methods and so on.3. Using
Arrays.asList()Another approach:
or, if you don’t need an
ArrayList, simply as:I prefer one of the above two methods.
4.
Collectionliterals (Java 7+)Assuming Collection literals go ahead in Java 7, you will be able to do this:
As it currently stands, I don’t believe this feature has been confirmed yet.
That’s it. Those are your choices. Pick one.