Array initialization syntax when not in a declaration

JavaArrays

Java Problem Overview


I can write:

AClass[] array = {object1, object2}

I can also write:

AClass[] array = new AClass[2];
...
array[0] = object1;
array[1] = object2;

but I can't write:

AClass[] array;
...
array = {object1, object2};

Why is this blocked by Java?

I know how to work around it, but from time to time it would be simpler.

For example:

public void selectedPointsToMove(cpVect coord) {

    if (tab == null) {
        if (arePointsClose(coord, point1, 10)) {
            cpVect[] tempTab = {point1};
            tab = tempTab;
        } else if (arePointsClose(point2, coord, 10)) {
            cpVect[] tempTab = {point2};
            tab = tempTab;
        } else {
            cpVect[] tempTab = {point1,point2};
            tab = tempTab;
        }
    }
}

This simple question that has been bugging me since I learned how to play with arrays in Java.

Java Solutions


Solution 1 - Java

> Why is this blocked by Java?

You'd have to ask the Java designers. There might be some subtle grammatical reason for the restriction. Note that some of the array creation / initialization constructs were not in Java 1.0, and (IIRC) were added in Java 1.1.

But "why" is immaterial ... the restriction is there, and you have to live with it.

> I know how to work around it, but from time to time it would be simpler.

You can write this:

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

Solution 2 - Java

I'll try to answer the why question: The Java array is very simple and rudimentary compared to classes like ArrayList, that are more dynamic. Java wants to know at declaration time how much memory should be allocated for the array. An ArrayList is much more dynamic and the size of it can vary over time.

If you initialize your array with the length of two, and later on it turns out you need a length of three, you have to throw away what you've got, and create a whole new array. Therefore the 'new' keyword.

In your first two examples, you tell at declaration time how much memory to allocate. In your third example, the array name becomes a pointer to nothing at all, and therefore, when it's initialized, you have to explicitly create a new array to allocate the right amount of memory.

I would say that (and if someone knows better, please correct me) the first example

AClass[] array = {object1, object2}

actually means

AClass[] array = new AClass[]{object1, object2};

but what the Java designers did, was to make quicker way to write it if you create the array at declaration time.

The suggested workarounds are good. If the time or memory usage is critical at runtime, use arrays. If it's not critical, and you want code that is easier to understand and to work with, use ArrayList.

Solution 3 - Java

I can't answer the why part.

But if you want something dynamic then why don't you consider Collection ArrayList.

ArrrayList can be of any Object type.

And if as an compulsion you want it as an array you can use the toArray() method on it.

For example:

            ArrayList<String> al = new ArrayList<String>();
            al.add("one");
            al.add("two");
            String[] strArray = (String[]) al.toArray(new String[0]);

I hope this might help you.

Solution 4 - Java

For those of you, who doesn't like this monstrous new AClass[] { ... } syntax, here's some sugar:

public AClass[] c(AClass... arr) { return arr; }

Use this little function as you like:

AClass[] array;
...
array = c(object1, object2);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJason RogersView Question on Stackoverflow
Solution 1 - JavaStephen CView Answer on Stackoverflow
Solution 2 - JavaprogradeView Answer on Stackoverflow
Solution 3 - JavaAmanpreetView Answer on Stackoverflow
Solution 4 - Javauser123View Answer on Stackoverflow