Print and Access List <String []>
I read the file and save it in t1. How to access elements in t1? When I try to print it, I get addresses instead of values. Also what is the difference between String and String[] ?
CSVReader reader = new CSVReader(new FileReader("src/new_acquisitions.csv")); List <String[]> t1 = reader.readAll(); int i = 0 while(i < t1.size()) { System.out.println(t1.get(i)); i++; } exit:
[Ljava.lang.String;@9304b1 [Ljava.lang.String;@190d11 [Ljava.lang.String;@a90653 [Ljava.lang.String;@de6ced String [] is an array of strings, so the reason does not print, as you would expect, try:
for (int i = 0; i < t1.size(); i++) { String[] strings = t1.get(i); for (int j = 0; j < strings.length; j++) { System.out.print(strings[j] + " "); } System.out.println(); } Or more concise:
for (String[] strings : t1) { for (String s : strings) { System.out.print(s + " "); } System.out.println(); } Or better yet:
for (String[] strings : t1) { System.out.println(Arrays.toString(strings)); } As Petar mentioned, your list is a list of string arrays, so you print the array, not its contents.
The lazy way to print the contents of an array is to convert the array to List<String> using java.utils.Arrays.toString() :
String[] stringArray=new String[] { "hello", world }; System.out.println(Arrays.toString(stringArray)); gives
["Hello World"]
You print a list with arrays. While List classes overload the toString () method to print each item, the array uses the default toString used by Object, which only prints the class name and identifier hash.
To print everything you need, iterate through the list and print each array using the Arrays.toString () array.
for(String[] ar:t1)System.out.print("["+Arrays.toString(ar)+"]"); Or you put each array in a list
List<List<String>> tt1 = new ArrayList<List<String>>(); for(String[] ar: t1)tt1.add(Arrays.asList(ar));//wraps the arrays in constant length lists System.out.println(tt1) You can print the contents of a list by simply translating the list into an array first and then using Arrays.toString, as shown below
System.out.println(Arrays.toString(your_list.toArray()); String[] is an array of strings. You print the address of the array - when you see [L , which means array. You should iterate over the elements of each array, instead of printing the address:
String[] temp = t1.get(i); for (int j = 0; j < temp.length; j++) System.out.println(temp[j]); As I said in your other question , when creating your own Record object, you can implement the toString() function to return a reasonable representation of this piece of information.