1

In python I can do the following:

n = 8  
a = []  
a += [1]*n

How can I do the equivalent in java with ArrayLists (without using a for loop..)?

List<T> list = new ArrayList<T>();
list.add(1);
list.add(2);
list.add(3);
// Some construct that is equivalent to a += [1]*n
2
  • For adding a list to the first one: List.addAll(Collection) Commented Nov 22, 2013 at 6:20
  • Sure, but that list does not exist yet. Collections.nCopies(8, 1) does what i want :) Commented Nov 22, 2013 at 7:08

1 Answer 1

5
final List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.addAll(Collections.nCopies(8, 1));

see Collections.nCopies()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.