Search code examples
javaarraylisttostringtoarray

Java arraylist to array, array to string error


I have to read data from text.txt file, but I have strange error, my output is: [Ljava.lang.String;@5f0a94c5.

The contents of text.txt file:

test::test.1::test.2
test2::test2.1::test2.2
test3::test3.1::test3.2

The code:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

public class test {
        public static void main(String[] args){
            ArrayList<String> data = new ArrayList<String>();

            try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
            String CurrLine;

            while((CurrLine = br.readLine()) != null) {
                data.add(CurrLine);
            }
            String[] dataArray = new String[data.size()];
            data.toArray(dataArray);
            Arrays.toString(dataArray);
            System.out.println(dataArray);


        } catch(FileNotFoundException ex) {
            System.out.println("FNFE");
        } catch(IOException ex) {
            System.out.println("IOE");
        }
    }
}

Solution

  • You need to use:

    System.out.println(Arrays.toString(dataArray));
    

    In your code, Arrays.toString(dataArray); does nothing as you don't do anything with its returned value.

    BTW, as @ZouZou pointed out, you can also print your ArrayList directly:

    System.out.println(data);