Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've tried to pass an initialization list {...} to a constructor and it didn't work. When I instead declared it in a method local variable (int[]) it worked flawlessly.

Why is that?

public class QuickSort {
    int[] a;

    public QuickSort(int[] a) {
        this.a = a;
    }

    public static void main(String[] args) {
        // ###################
        // ###    WORKS     ##
        // ###################
        int[] a = {8,12,79,12,50,44,8,0,7,289,1};
        QuickSort sort = new QuickSort(a);

        // ###################
        // ### DOESN'T WORK ##
        // ###################
        //QuickSort sort = new QuickSort({8,12,79,12,50,44,8,0,7,289,1});
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
187 views
Welcome To Ask or Share your Answers For Others

1 Answer

When declaring an int[] and assigning {1, 2, 3} the compiler knows you want to create an int[] as it's spelled out right there.

In the latter case where you stick the array directly into the method call you would have to use

QuickSort sort = new QuickSort(new int[] {8,12,79,12,50,44,8,0,7,289,1});

to tell the compiler what your array is.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...