定义一个商品类,商品有价格和名称属性,使用ArrayList集合,对其添加3个商品对象,并使用Iterator遍历输出集合中商品
时间: 2024-01-22 13:18:55 浏览: 156
好的,以下是Java的代码实现:
```
import java.util.ArrayList;
import java.util.Iterator;
public class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public static void main(String[] args) {
ArrayList<Product> productList = new ArrayList<>();
productList.add(new Product("Apple", 3.99));
productList.add(new Product("Banana", 2.99));
productList.add(new Product("Orange", 4.99));
Iterator<Product> iterator = productList.iterator();
while (iterator.hasNext()) {
Product product = iterator.next();
System.out.println("Product name: " + product.getName() + ", price: " + product.getPrice());
}
}
}
```
运行该程序可以得到以下输出结果:
```
Product name: Apple, price: 3.99
Product name: Banana, price: 2.99
Product name: Orange, price: 4.99
```
阅读全文