Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a default value for items list?

Tags:

java

I'm trying to convert some python code to java and need to setup a default value of a list. I know the default value, the size of the list and my goal is to setup a default value and then later in my program change them. In python I simply do this(to create 10 items with a value of zero):

list = [0]*10  

I am trying to do:

List<Integer> list1 = Arrays.asList(0*10); // it just multiples 0 by 10.

It doest work, I know I can do something like this:

for(int i = 0;i<10;i++)
{
  list1.add(0); 
}

I was wondering if there was an better way(instead of the for loop)?

like image 863
Lostsoul Avatar asked Mar 15 '12 19:03

Lostsoul


People also ask

How do you add a value to an ArrayList by default?

Java developers use the Arrays. asList() method to initialize an ArrayList. Using asList() allows you to populate an array with a list of default values. This can be more efficient than using multiple add() statements to add a set of default values to an ArrayList.

How do I set default value in SAP?

To assign a default value to a parameter, you use the following syntax: PARAMETERS p ...... DEFAULT f ...... Default value f can be either a literal or a field name.

What is default value of list in Java?

ArrayLists have no default values.


1 Answers

Arrays.fill lets you avoid the loop.

Integer[] integers = new Integer[10];
Arrays.fill(integers, 0);
List<Integer> integerList = Arrays.asList(integers);
like image 71
Mike Samuel Avatar answered Oct 03 '22 06:10

Mike Samuel