List of items with the same values

I create a list of items from a file

BufferedReader reader = new BufferedReader(
    new InputStreamReader(new FileInputStream("H:/temp/data.csv")));
try {
    List<Item> items = new ArrayList<Item>();
    Item item = new Item();

    String line = null;
    while ((line = reader.readLine()) != null) {
        String[] split = line.split(",");

        item.name = split[0];
        item.quantity = Integer.valueOf(split[1]);
        item.price = Double.valueOf(split[2]);
        item.total = item.quantity * item.price;

        items.add(item);
    }

    for (Item item2 : items) {
        System.out.println("Item: " + item2.name);
    }
} catch (IOException e) {
    reader.close();

    e.printStackTrace();
}

The problem is that the list displays the last line in the file as a value for all elements.

+3
source share
1 answer

The problem with your code is to create only one instance of the Item ( Item item = new Item) object , and the same instance is added to the list again and again.

You need to create a new instance Itemfor each line in the file and add it to the list, as shown below.

Fix:

List<Item> items = new ArrayList<Item>();

String line = null;
while ((line = reader.readLine()) != null) {
    String[] split = line.split(",");

    Item item = new Item(); // New Item is created for every line
    item.name = split[0];
    item.quantity = Integer.valueOf(split[1]);
    item.price = Double.valueOf(split[2]);
    item.total = item.quantity * item.price;

    items.add(item);
}
+13
source

Source: https://habr.com/ru/post/1782991/


All Articles