I've been trying to save a list of data as Strings, but when I try a method .toString on List, it returns address in memory instead of data.
public class Item {
Integer price = 20;
Integer modelNumber = 100;
String description = "Description";
String title = "Title";
Boolean wasBought = true;
}
public static void main(String[] args) {
List<Item> data = new ArrayList<>();
data.add(new Item());
System.out.println(data.toString());
}
CodePudding user response:
You need to override toString function in your Item class. Add the following snippet into your Item class:
@Override
public String toString() {
return "Item{"
"price=" price
", modelNumber=" modelNumber
", description='" description '\''
", title='" title '\''
", wasBought=" wasBought
'}';
}
Output:
[Item{price=20, modelNumber=100, description='Description', title='Title', wasBought=true}]
CodePudding user response:
You can convert List to json format string by json utils, e.g. jackson or fastjson, in case you may need to convert it to Objects later.
CodePudding user response:
Simply use Lombok (Add Lombok jar into classpath) @ToString annotate for Item class, it will do the needful output https://projectlombok.org/features/ToString
