Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 具有相同值的项目列表_Java_List - Fatal编程技术网

Java 具有相同值的项目列表

Java 具有相同值的项目列表,java,list,Java,List,我正在从文件创建项目列表 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; whi

我正在从文件创建项目列表

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();
}
BufferedReader reader=新的BufferedReader(
新的InputStreamReader(新文件InputStream(“H:/temp/data.csv”);
试一试{
列表项=新建ArrayList();
项目=新项目();
字符串行=null;
而((line=reader.readLine())!=null){
String[]split=line.split(“,”);
item.name=split[0];
item.quantity=整数.valueOf(拆分[1]);
item.price=Double.valueOf(拆分[2]);
item.total=item.quantity*item.price;
项目。添加(项目);
}
用于(项目2:项目){
System.out.println(“项:”+item2.name);
}
}捕获(IOE异常){
reader.close();
e、 printStackTrace();
}

问题是列表将文件中的最后一行显示为所有项的值。

代码的问题是您只创建了项对象的一个实例(
Item Item=new Item
),同一实例会一次又一次地添加到列表中

您需要为文件中的每一行创建
项的新实例
,并将其添加到列表中,如下所示

修正:

List items=new ArrayList();
字符串行=null;
而((line=reader.readLine())!=null){
String[]split=line.split(“,”);
Item Item=new Item();//为每行创建新项
item.name=split[0];
item.quantity=整数.valueOf(拆分[1]);
item.price=Double.valueOf(拆分[2]);
item.total=item.quantity*item.price;
项目。添加(项目);
}
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);
}