6

Is there a more convenient way to initialize an array of objects than doing this?

SomeClass[] someArray = new SomeClass[100];
//...
for (int i = 0; i < someArray.length; i++) { 
  someArray[i] = new SomeClass();
}
// ...
8
  • If you like typing : String[] stringArray = {"1","2","3", ...., "100"} Commented Apr 19, 2013 at 17:55
  • 1
    I don't see anything wrong with the way you're doing this. Commented Apr 19, 2013 at 17:57
  • Do you want avoid NullPointerException? What about if you using a java.util.List or java.util.Map? Commented Apr 19, 2013 at 17:57
  • @NoobUnChained that won't compile, savvy? ;) Commented Apr 19, 2013 at 17:59
  • 2
    Never call any of the constructors of String. Since string instances are immutable, it macks no sense to construct new ones. If you want to use a loop like this, just set each entry to "". Do you really need to do this task? It might not be necessary. Commented Apr 19, 2013 at 18:00

6 Answers 6

8

Use Arrays.fill()

String[] stringArray = new String[100];
Arrays.fill(stringArray, "");

It's not any faster since it iterates over the array just like you did, but it is more convenient.

Arrays.fill() code

public static void fill(Object[] a, int fromIndex, int toIndex, Object val) {
    rangeCheck(a.length, fromIndex, toIndex);
    for (int i=fromIndex; i<toIndex; i++)
        a[i] = val;
}
Sign up to request clarification or add additional context in comments.

3 Comments

I will just add that this will fill array with the same object
So? Strings are immutable; it doesn't matter.
@LouisWasserman In terms of Strings it wont matter that much but if OP would like to fill array with different types of objects fill wont do the trick. Anyway it is not like I am saying that there is something wrong with this answer, just adding some more info.
2

Because of the immutability of String in Java, your question is a bit strange. The primary thrust suggests you are looking for this:

String[] arr = new String[100];
Arrays.fill(arr, new String());//Array utility

However, this does not actually net you anything, because you will have to effectively create a new String object whenever you replace one of those array items with a different String. This means that the act of creating a new String() is redundant and therefore less efficient.

This begs the question: why are you doing this? Is it to ensure that there is a valid object being returned? Or that the object in the array is actually a String? If the latter, make use of generics:

List<String> arr = new ArrayList<String>();

This solves the same problem and nets you benefits of object-orientation. It is generally recommended you stay away from primitive arrays if you can: object-based arrays are far more usable, leading to cleaner code and often more efficient programs.

If you are using a mutable type, and the point of pre-filling is to ensure that an object exists when it's retrieved from the array, the best way to handle this is to actually use exceptions on the receiving end, for two reasons: the first being that you save memory by not allocating memory before you actually need it (and all the attendant savings that go along with that) and the second being that there is little stopping an array from having an element set to null, so you have to check anyway:

try {
  SomeObject myObj = arr.get(idx);
  myObj.doSomethingFun();//will fail if this is null!
} catch (NullPointerException e) {
  //do something intelligent like return a fail case.
}

Note that while exceptions carry overhead if they catch an actual error, they have no overhead until that point. For this reason you don't want to use them for flow-of-control, but you do want to use them (more than you probably do) to catch edge cases that don't make sense.

2 Comments

You're of course right. Using String wasn't the best example. Let's say it is some mutable type...
@user1967864 I posted answer for creating distinct objects that can be useful with mutable types. Also, consider editing question.
2

This isn't quicker, but its less code:

String[] stringArray = new String[100];
Arrays.fill(stringArray, "");

Comments

2

So, you told you want to create array of distinct objects. Then there must be a default constructor or a factory that you pass in. I'll show code for first case - when you can call empty constructor with Class<...>.newInstance():

import java.lang.reflect.Array;
// ... in a class:
@SuppressWarnings("unchecked")
public static <T> T[] initializedArray(int size, Class<T> classHint) throws java.lang.Exception {
   T[] result = (T[]) Array.newInstance(classHint, size);
   for (int i = 0; i < size; ++i) {
      result[i] = classHint.newInstance();
   }
   return result;
}

Example usage here: http://ideone.com/pbTFq9

Comments

1

you can declare like

String[] array;
...
array = new String[]{object1, object2};

Comments

1

Java 8 Streams supports constructing and initializing an array of SomeClass with one line.

SomeClass[] array = IntStream.range(0, 100).mapToObj(i -> new SomeClass()).toArray(SomeClass[]::new);

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.