Reputation: 21
there are many posts on how to display the elements of LinkedList<String>, but I can't find something that I understand for LinkedList<String[]>.
The following code shows the output: LinkedList:[[Ljava.lang.String;@5305068a, [Ljava.lang.String;@1f32e575
whereas I'm looking for the output: LinkedList:[[Audi SQ5,341], [LandRover Discovery,306]].
and I don't want to overwrite the toString().
Code:
LinkedList<String[]> cars2 = new LinkedList<>();
String[] split_result = new String[2];
split_result = "Audi SQ5,341".split(",");
cars2.add(split_result);
split_result = "LandRover Discovery,306".split(",");
cars2.add(split_result);
// Displaying the size of the list
System.out.println("The size of the linked list is: " + cars2.size());
// Displaying the Strings in the linkedlist ??? (not their addresses)
System.out.println("LinkedList:" + cars2);
cars2.forEach(element -> System.out.println(element));
Upvotes: 0
Views: 173
Reputation: 14964
Your problem is that while default Java collections like LinkedList implement a nice toString to print their memebers, arrays do not. So either you have to iterate over your collection and print the results yourself, as some other answers suggest, or you have to put objects into your LinkedLists that have a nice toString implementation. Those can either be collections themselves List<List<String>>
, or you can define a class to contain your data.
class CarInfo {
// these should be encapsulated with getters/setters, I'm being lazy.
public String model;
public String value; // I don't know what this represents, or if it's a string or int
public void toString() { return model + ", " + value; }
}
If you use Lombok, this is very easy with the @Data annotation, which will generate toString and getters/setters for you.
@Data
class CarInfo {
String model;
String value;
}
However, it won't be exactly the same as your desired output. If you want it specifically formatted with the brackets as you described, you'd have to do your own toString anyway.
Upvotes: 0
Reputation: 623
I would use a Java Stream for that. It has the helpful joining collector:
LinkedList<String[]> cars2 = new LinkedList<>();
String output = cars2
.stream()
.map(Arrays::toString)
.collect(Collectors.joining(", ", "[", "]"));
Upvotes: 1