public class Goods {//商品实体类private String number;//商品编号private String name;//商品价格private double price;//商品单价private int quantity;//商品数量public void setNumber(String number) {this.number number;}public String getNumber() {return number;}public void setName(String name) {this.name name;}public String getName() {return name;}public void setPrice(double price) {this.price price;}public double getPrice() {return price;}public void setQuantity(int quantity) {this.quantity quantity;}public int getQuantity() {return quantity;}}
测试结果
//treesetimport java.util.HashSet;import java.util.Iterator;import java.util.Set;import java.util.UUID;//set接口public class test60{public static void main(String[] args){//Set goodssetnew HashSet(18);//初始容量不够用会自动扩展Set goodssetnew HashSet(16);Goods goods0new Goods();goods0.setName("肥皂");goods0.setNumber(UUID.randomUUID().toString());goods0.setQuantity(20000);Goods goods1new Goods();goods1.setName("洗发水");goods1.setNumber(UUID.randomUUID().toString());goods1.setQuantity(20000);Goods goods2new Goods();goods2.setName("运动鞋");goods2.setNumber(UUID.randomUUID().toString());goods2.setQuantity(20000);Goods goods3new Goods();goods3.setName("运动鞋");goods3.setNumber(UUID.randomUUID().toString());goods3.setQuantity(2000);goodsset.add(goods2);goodsset.add(goods1);goodsset.add(goods0);goodsset.add(goods3);Iterator iteratorgoodsset.iterator();while(iterator.hasNext()){Goods g(Goods)iterator.next();System.out.println(g.getName()"\t"g.getNumber()"\t"g.getQuantity());}for(Object O:goodsset){System.out.println(((Goods)O).getName());}//将set集合中的所有元素封装为Object数组返回Object[] objsgoodsset.toArray();for(int i0;i