I'm reading in a file and storing it in t1. How do I access the elements in t1? When I try to print it I get addresses instead of values. Also whats 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++;
}
output:
[Ljava.lang.String;@9304b1
[Ljava.lang.String;@190d11
[Ljava.lang.String;@a90653
[Ljava.lang.String;@de6ced
String[] is an array of strings, hence the reason it is not printing 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 Arrays of Strings, so you are printing out the array, not the array contents.
A lazy way to print out the array contents is to convert the array to a List<String>
with 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 the List classes overload the toString() method to print each element, the array uses the default toString used by Object which only prints the classname and the identity hash.
To print all you either have to iterate through the List and print each array with Arrays.toString().
for(String[] ar:t1)System.out.print("["+Arrays.toString(ar)+"]");
Or you put each array into 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With