路过为什么{A,B,C}的方法不起作用? [英] Why passing {a, b, c} to a method doesn't work?

查看:147
本文介绍了路过为什么{A,B,C}的方法不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图传递一个初始化列表{...}一个构造函数,它没有工作。
当我代替的方法局部变量声明它(INT [])它的工作完美无缺。

这是为什么?

 公共类快速排序{
    INT []一个;    公共快速排序(INT [] A){
    this.a =一;
    }    公共静态无效的主要(字串[] args){
    // ###################
    // ### WORKS ##
    // ###################
    INT [] A = {} 8,12,79,12,50,44,8,0,7,289,1;
    快速排序排序=新的快速排序(一);    // ###################
    // ###不工作##
    // ###################
    //快速排序排序=新的快速排序({8,12,79,12,50,44,8,0,7,289,1});
    }
}


解决方案

在声明一个 INT [] 和分配 {1,2,3 } 编译器知道你想创建一个 INT [] 因为它规定了在那里。

在那里您可以直接粘在数组的方法后一种情况叫你将不得不使用

 快速排序排序=新的快速排序(新INT [] {8,12,79,12,50,44,8,0,7,289,1});

要告诉编译器阵列是什么。

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});
    }
}

解决方案

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.

这篇关于路过为什么{A,B,C}的方法不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆