0

I try to read data from a text file and add the data into an arraylist whose element is 7-number array. 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. I guess the reason might be the function has to be called in the main method which is static. 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.

enter image description here

1
  • 1
    read needs to be static (or invoked via new readFile().read()). Or just inline read into main. Commented Feb 18, 2016 at 8:34

1 Answer 1

4

Move the declaration of temp inside the while loop:

    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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. So it's not the reason about static method, just I have wrong code. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.