Java arraylist to array, array to string error

209 Views Asked by At

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");
        }
    }
}
2

There are 2 best solutions below

5
On BEST ANSWER

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);
0
On

Your code : System.out.println(dataArray); will output the hashcode value for the object dataArray. Any array in Java does not override equals() method. As a result, when you try to print the value of the array object, java.lang.Object.equals() method is invoked which prints the hashcode of the object .

Instead try using System.out.println(Arrays.toString(dataArray));