Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of items with same values

Tags:

java

list

I'm creating 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();
}

Problem is the list is displaying the last line in the file as the value for all items.

like image 229
user559780 Avatar asked Nov 25 '25 06:11

user559780


1 Answers

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

You need to create a new instance of the Item for every 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);
}
like image 161
Arun P Johny Avatar answered Nov 27 '25 23:11

Arun P Johny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!