写入数组

时间:2015-11-21 00:33:02

标签: java arrays list loops writing

我有一个方法需要从对象中获取数年并将其写入数组。这就是我到目前为止所做的:

    public int[] getYears() {   

    int[] years = null;

    for (RainfallYear rainfall : rainfallYears) {
        int year = rainfall.getYear();
        //insert year into int[] years array and return.
    }

    return years;
}

-

RainfallYear是一个年份和一年中降雨量值的对象:

public RainfallYear(int year, double[] rainfallMonths) {
    super();
    this.year = year;
    this.rainfallMonths = rainfallMonths;
}

这就是它在视觉上的样子:

1914,50.9,87,115.8,32.3,47.1,56.6,97.1,63.9,48.1,62.4,110.3,190.8

rainfallYears是RainfallYear对象数组的名称:

private RainfallYear[] rainfallYears = null;

我正在努力将“提取的”年份插入到数组中以实现int [] getYears方法的功能 - 返回数组的年份。

这是我之前尝试这样做的,但我不认为我所做的是正确的:

List<Integer> yearsList = null;
    for (int i = 0; i < rainfallYears.length; i++) {
        yearsList = new ArrayList<Integer>();
        yearsList.add(new RainfallYear(i, null).getYear());
    }

    int[] yearsArray = new int[yearsList.size()];
    for (int i = 0; i < yearsList.size(); i++) {
        yearsArray[i] = yearsList.get(i);
    }

    return yearsArray;

2 个答案:

答案 0 :(得分:1)

您正在重新初始化循环的每次迭代yearsList,每次都会为其提供新数据。

List<Integer> yearsList = null;
for (int i = 0; i < rainfallYears.length; i++) {
    yearsList = new ArrayList<Integer>();
    yearsList.add(new RainfallYear(i, null).getYear());
}

相反,在循环之外初始化列表就像对阵列一样。

List<Integer> yearsList = new ArrayList<Integer>();
for (int i = 0; i < rainfallYears.length; i++) {           
    yearsList.add(new RainfallYear(i, null).getYear());
}

答案 1 :(得分:1)

在此for循环中,您为每次迭代创建一个新的ArrayList

List<Integer> yearsList = null;
for (int i = 0; i < rainfallYears.length; i++) {
    yearsList = new ArrayList<Integer>();
    yearsList.add(new RainfallYear(i, null).getYear());
}

int[] yearsArray = new int[yearsList.size()];
for (int i = 0; i < yearsList.size(); i++) {
    yearsArray[i] = yearsList.get(i);
}

return yearsArray;

把它拿出来

List<Integer> yearsList = new ArrayList<Integer>();
for (int i = 0; i < rainfallYears.length; i++) {
    yearsList.add(new RainfallYear(i, null).getYear());
}

int[] yearsArray = new int[yearsList.size()];
for (int i = 0; i < yearsList.size(); i++) {
    yearsArray[i] = yearsList.get(i);
}

return yearsArray;

但是ArrayList似乎没用,因为yearsList.get(i)会给你#34;年&#34;那一年是i中的new RainfallYear(i, null)i我从0变为rainfallYears.length。 那你为什么不这样做呢:

int[] yearsArray = new int[rainfallYears.length];
for (int i = 0; i < rainfallYears.length; i++) {
    yearsArray[i] = i;
}