Java在构造函数中初始化一个int数组 [英] Java Initialize an int array in a constructor

查看:235
本文介绍了Java在构造函数中初始化一个int数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个班级,在那个班级我有这个:

I have a class and in that class I have this:

 //some code
 private int[] data = new int[3];
 //some code

然后在我的构造函数中:

Then in my constructor:

public Date(){
    data[0] = 0;
    data[1] = 0;
    data[2] = 0;
}

如果我这样做,一切都会好的。默认数据值已初始化但如果我这样做:

If I do this, everything is OK. Default data values are initialized but if I instead do this:

public Date(){
    int[] data = {0,0,0};
}

它说:

Local variable hides a field

为什么?

什么是在构造函数中初始化数组的最佳方法?

Whats the best way to initialize an array inside the constructor?

谢谢

推荐答案

private int[] data = new int[3];

这已经将数组元素初始化为0.你不需要在构造函数中重复这一点。

This already initializes your array elements to 0. You don't need to repeat that again in the constructor.

在你的构造函数中它应该是:

In your constructor it should be:

data = new int[]{0, 0, 0};

这篇关于Java在构造函数中初始化一个int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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