Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Saving List<T> as String

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());
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading