gpt4 book ai didi

java - 写入数组

转载 作者:行者123 更新时间:2023-12-02 04:10:30 24 4
gpt4 key购买 nike

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

    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;

最佳答案

在此 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) 会给你“年份”,而那一年就是 i new RainfallYear(i, null) 并且 i i 从 0 变为 rainfallYears.length。那么为什么不直接这样做呢:

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

关于java - 写入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33838295/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com