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

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

java - Why passing {a, b, c} to a method doesn't work?

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...