[英]How can I add data into an arraylist in static main method
I try to read data from a text file and add the data into an arraylist whose element is 7-number array. 我尝试从文本文件中读取数据,并将数据添加到元素为7号数组的arraylist中。 But all the elements of the arraylist always turn to the value which is read last time, which means the last data read replace all the elements in the list. 但是arraylist的所有元素总是变成上次读取的值,这意味着最后读取的数据将替换列表中的所有元素。 I guess the reason might be the function has to be called in the main method which is static. 我想原因可能是必须在静态的main方法中调用该函数。 How can I add the data successfully? 如何成功添加数据?
package main;
import java.util.Locale;
import java.util.Scanner;
import javax.swing.JFileChooser;
import java.util.ArrayList;
import java.io.*;
public class readFile {
public static void main(String args[]){
read();
}
public void read()throws Exception{
Scanner input = new Scanner(new File("./src/sample.txt"));
input.useLocale(Locale.US);
double[] temp = new double[7];
ArrayList<double[]> pointList= new ArrayList<double[]>();
while(input.hasNext()){
for (int i=0;i<=6;i++)
{
temp[i]=input.nextDouble();
}
pointList.add(temp);
}
}
}
The data in text file is as the bottom in the figure, while the result is just same for each element. 文本文件中的数据位于图中的底部,而每个元素的结果都相同。
Move the declaration of temp
inside the while loop: 在while循环内移动temp
的声明:
ArrayList<double[]> pointList= new ArrayList<double[]>();
while(input.hasNext()){
double[] temp = new double[7];
for (int i=0;i<7;i++) // Don't make it more confusing by using "6" here.
{
temp[i]=input.nextDouble();
}
pointList.add(temp);
}
Otherwise, you are just repeatedly adding the same array into the list, meaning you are overwriting the elements. 否则,您只是重复将同一数组添加到列表中,这意味着您将覆盖元素。
Adding an item to a list doesn't make a copy of it: it just adds the reference to the item to the list. 将项目添加到列表不会复制该项目:它只是将对该项目的引用添加到列表中。 As such, subsequent changes to that item are reflected in the item in the list. 这样,对该项目的后续更改将反映在列表中的项目中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.