泛型的一个重要好处是能够简单而安全地创建复杂的模型,比如组装多层容器时,其泛型就能保障其安全了。
代码例子:
//商品
class Product
{
private final int id;
private String description;
private double price;
public Product(int id, String description, double price)
{
super();
this.id = id;
this.description = description;
this.price = price;
System.out.println(toString());
}
@Override
public String toString()
{
return id+": "+description+", price: $"+price;
}
public void priceChange(double change)
{
price+=change;
}
//这里用静初始化不单单为方便调用,更重要的是共用这个对象减少内存开销
public static Generator<Product> generator=new Generator<Product>()
{
private Random random=new Random(47);
@Override
public Product next()
{
return new Product(random.nextInt(1000),"Test",Math.round(random.nextDouble()*1000.0)+0.99);
}
};
}
//货架,让其摆设多个商品
@SuppressWarnings("serial")
class Shelf extends ArrayList<Product>
{
public Shelf(int nProducts)
{
//生产器工具类填充这个货架,其元素为多个Product商品
Generators.fill(this, Product.generator, nProducts);
}
}
//走廊摆设多个货架
@SuppressWarnings("serial")
class Aisle extends ArrayList<Shelf>
{
public Aisle(int nShelves,int nProducts)
{
//添加多个货架
for(int i=0;i<nShelves;i++)
add(new Shelf(nProducts));
}
}
//商店摆设多个走量
@SuppressWarnings("serial")
public class Store extends ArrayList<Aisle>
{
public Store(int nAisles,int nShelves,int nProducts)
{
//添加多个走廊
for(int i=0;i<nAisles;i++)
add(new Aisle(nShelves, nProducts));
}
@Override
public String toString()
{
//用字符容器装其内容
StringBuilder builder=new StringBuilder();
for(Aisle a:this)
for(Shelf s:a)
for(Product p:s)
{
builder.append(p);
builder.append("\n");
}
return builder.toString();
}
public static void main(String[] args)
{
System.out.println(new Store(2, 3, 2));
}
}
运行结果:
258: Test, price:
400.99861:Test,price:
160.99
868: Test, price:
417.99207:Test,price:
268.99
551: Test, price:
114.99278:Test,price:
804.99
520: Test, price:
554.99140:Test,price:
530.99
704: Test, price:
250.99575:Test,price:
24.99
674: Test, price:
440.99826:Test,price:
484.99
258: Test, price:
400.99861:Test,price:
160.99
868: Test, price:
417.99207:Test,price:
268.99
551: Test, price:
114.99278:Test,price:
804.99
520: Test, price:
554.99140:Test,price:
530.99
704: Test, price:
250.99575:Test,price:
24.99
674: Test, price:
440.99826:Test,price:
484.99