15

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)?

Lostsoul
  • 25,013
  • 48
  • 144
  • 239
  • Could you use an array instead of a list? – Mark Byers Mar 15 '12 at 19:58
  • @MarkByers It doesn't really matter but I read that lists have better performance is the size is fixed so that was why I went that route. Its not terribly important what I use, although since I'm learning I just want to learn the right tools for the right tasks. – Lostsoul Mar 15 '12 at 20:00
  • 1
    @learningJava: No, it's the other way round - *arrays* have a fixed size. But lists are generally more fleixble. – Jon Skeet Mar 15 '12 at 20:02
  • @JonSkeet opps sorry. I think I need to stop drinking and learning java :-) – Lostsoul Mar 15 '12 at 20:04

9 Answers9

29

Arrays.fill lets you avoid the loop.

Integer[] integers = new Integer[10];
Arrays.fill(integers, 0);
List<Integer> integerList = Arrays.asList(integers);
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
  • 2
    Note that that list will then be a *fixed* size - you can't add to it or remove from it. That may or may not be what's wanted. – Jon Skeet Mar 15 '12 at 19:59
  • @JonSkeet, quite right. I interpreted that as desired because of "I know the default value, the size of the list ...". – Mike Samuel Mar 15 '12 at 20:00
  • This is correct, it is a fixed size which was why I choose lists in the first place. I'm a little confused, I understand the first two lines, you made a list that holds 10 items and then used arrays.fill to set it all to zeros, why is the third line needed? – Lostsoul Mar 15 '12 at 20:03
  • @learningJava, If you want to work with a `List`, then the third line is necessary. Arrays and lists are different types, and you can't always use an array with APIs that require `List`s or `Collection`s or vice-versa because Java is not "duck-typed" the way Python is. If you are happy with an array, be aware that there is a difference between `Integer[]` and `int[]` and that the latter is usually preferable. – Mike Samuel Mar 15 '12 at 20:06
  • @learningJava, http://stackoverflow.com/a/716641/20394 explains collections vs arrays in Java and why you might want to use one over the other. – Mike Samuel Mar 15 '12 at 20:09
  • Thanks Mike, your answer was very helpful as well as your link. I'm also curious to the differences between Integer and int, so I'll do some research right now the subject(I have been using them indifferently so far) – Lostsoul Mar 15 '12 at 20:13
  • @learningJava, You should read up on `int` vs `Integer`. Be aware that `==` when used with `Integer` is the same as `is` in Python. In Python `1 == True` but `1 is not True`. – Mike Samuel Mar 15 '12 at 20:15
  • @learningJava, http://stackoverflow.com/questions/8916051/why-in-java-is-there-a-wrapper-for-every-primitive-type discusses `Integer` vs `int`. – Mike Samuel Mar 15 '12 at 20:17
  • Thanks so much Mike. I asked one question and got answers to questions I didn't even have yet(but would in the future). You gave me a lot of study material. Thanks so much! – Lostsoul Mar 15 '12 at 20:19
18

Collections.nCopies is your friend if you need a list instead of an array:

List<Integer> list = Collections.nCopies(10, 0);

If a mutable list is needed, wrap it:

List<Integer> list = new ArrayList<>(Collections.nCopies(10, 0));
Michel Jung
  • 2,966
  • 6
  • 31
  • 51
3

Maybe you just need an array?

int[] array = new int[10];

You need a list if you need to change the size of it dynamically. If you don't need this feature, an array may suit your needs, and it will automatically initialize all the values to 0 for you.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
3

You can try:

List<Integer> list1 = Arrays.asList(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);

There are 10 zeroes. You need to know the number of elements at the compile time, but you have only one line. If you don't know the number of elements at compile time, then you can use the suggested Arrays.fill() approach.

Jakub Zaverka
  • 8,816
  • 3
  • 32
  • 48
  • 2
    Please don't make your code's maintainers count 0's. Comments won't help since a maintainer can't assume they're consistent with the code. – Mike Samuel Mar 15 '12 at 20:12
  • I was really really trying to avoid that. I'm pretty lazy and don't like typing that much. Plus my data is a few thousand zeros so I might void my keyboard warranty if I type that much :-) – Lostsoul Mar 15 '12 at 20:15
  • Yeah, that was really a wild shot for fewer init values. I don't like the code, either. – Jakub Zaverka Mar 15 '12 at 20:20
2

There's nothing built into the standard libraries, as far as I'm aware. But you can easily write such a method once and call it from wherever you want. For example:

public static <T> List<T> newArrayList(T value, int size) {
    List<T> list = new ArrayList<T>(size);
    for (int i = 0; i < size; i++) {
        list.add(value);
    }
    return list;
}

If you never want to change the size of the list (i.e. add or remove elements), Mike Samuel's answer is probably more efficient. Also note that if you're using a mutable type, you may not get what you want:

List<StringBuilder> list = newArrayList(new StringBuilder(), 10);
list.get(0).append("Foo");
System.out.println(list.get(5)); // Prints "Foo"

... as each element in the list will be a reference to the same object.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

If you are using java 8 or above you can do the following. Here are the required imports:

import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

Here is the code to get it to work

List<Integer> integers = new ArrayList() {{
      IntStream.range(0,5).forEach((i) ->  add(0));
}};

The double braces are not a mistake they are required! I hope this helps.

GetBackerZ
  • 448
  • 5
  • 12
0
List<Integer> list1 = IntStream.range(0, 10)
                         .mapToObj(i -> 0)
                         .collect(Collectors.toList());
Yosi Dahari
  • 6,794
  • 5
  • 24
  • 44
Tamir Adler
  • 341
  • 2
  • 14
-2

In Java, not really. Java is relatively verbose when it comes to this sort of stuff, so there isn't much you can do that is simple, other than a loop like you have.

cdeszaq
  • 30,869
  • 25
  • 117
  • 173
-2

I would stick with the for loop.

BTW... 0*10 = 0 so just enter in the amount you need instead

ArrayList<Integer> list = new ArrayList<Integer>(10);

amlane86
  • 668
  • 4
  • 15
  • 24