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)?
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.
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.
ArrayLists have no default values.
Arrays.fill
lets you avoid the loop.
Integer[] integers = new Integer[10];
Arrays.fill(integers, 0);
List<Integer> integerList = Arrays.asList(integers);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With