Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

java - List of items with same values

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...