Asked  6 Months ago    Answers:  5   Viewed   25 times

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.

 Answers

25

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};
Tuesday, June 1, 2021
 
WooDzu
answered 6 Months ago
91

Because the guys in the C++ committee decided so.

The technical reason is that the first expression that is used to initialize size is a constant expression and it can be computed during compilation. This means that the compiler can also know how big the array is going to be and the allocation (in this case "reservation" may be a more appropriate term) can be done at compile time.

In the second case instead the expression is not a constant expression (given the C++ definition) and this revervation is not possible.

The fact that in the second case the value is indeed fixed by the time size is initialized is totally irrelevant. The rules are base on the "kind of expression" and the second expression uses mutable variables and thus the compiler considers it non-constant.

Allowing the second form for compile-time initialization would require a flow analysis because it would need to distinguish between

int a = 2;
const int size = a;

and

int a = foo();
const int size = a;

where the expression involving size is indeed identical.

Wednesday, June 2, 2021
 
Student
answered 6 Months ago
55

Arrays in Java store one of two things: either primitive values (int, char, ...) or references (a.k.a pointers).

So, new Integer[10] creates space for 10 Integer references only. It does not create 10 Integer objects (or even free space for 10 Integer objects).

Incidentally that's exactly the same way that fields, variables and method/constructor parameters work: they too only store primitive values or references.

Monday, June 14, 2021
 
fret
answered 6 Months ago
53

Your first call to Arrays.asList is actually returning a List<double[]> - it's autoboxing the argument, because a double[] isn't a T[]... generics don't allow for primitive types as type arguments.

If you want to convert a double[] into a List<Double>, you either need to do it manually or use a third-party library to do it. For example:

public List<Double> toList(double[] doubles) {
    List<Double> list = new ArrayList<>(doubles.length);
    for (double x : doubles) {
        list.add(x);
    }
    return list;
}

Note that unlike Arrays.asList any subsequent changes to the array will not be reflected in the list or vice versa - it's a copy, not a view.

Saturday, August 7, 2021
 
DanMark
answered 4 Months ago
88

Look at JLS on Arrays:

The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both.

and

Brackets are allowed in declarators as a nod to the tradition of C and C++. The general rules for variable declaration, however, permit brackets to appear on both the type and in declarators, so that the local variable declaration:

float[][] f[][], g[][][], h[];  // Yechh!

is equivalent to the series of declarations:

float[][][][] f;
float[][][][][] g;
float[][][] h;

So for example:

int []p, q[];

is just

int[] p, q[]

which is in fact

int p[]; int q[][]

The rest are all similar.

Thursday, August 12, 2021
 
pwaring
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share