这个程序实现了集合中的数据相加,和集合的增删
//泛型封装类
public class Phone {
String name="";
int id=0;
int price=0;
int count = 0;
public Phone( int id,String name, int price,int count) {
super();
this.name = name;
this.id = id;
this.count = count;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public String toString() {
return id+"\t"+name+"\t"+price+"\t"+count ;
}
}
实现方法类
public static void main(String[] args) {
List<Phone> mList = new ArrayList<Phone>();
List<Phone> buy = new ArrayList<Phone>();
mList.add(new Phone(1, "华为G9", 1699, 50));
mList.add(new Phone(2, "荣耀5x", 1099, 50));
mList.add(new Phone(3, "华为笔记本", 6688, 50));
mList.add(new Phone(4, "荣耀5c", 899, 50));
Scanner mScanner = new Scanner(System.in);
int iscontinue = 0;
boolean isNewAdd = true;
do {
System.out.println("----------------商场-------------------");
for (Phone phone : mList) {
System.out.println(phone);
}
System.out.println("请输入需要购买的商品:");
int buyId = mScanner.nextInt();
System.out.println("请输入需要购买的数量:");
int buyCount = mScanner.nextInt();
//判断buy的这个集合中是否有我们已经购买过的东西,买过了就把数量加起来,把原来的删了在从新加进集合
for (int i = 0; i < buy.size(); i++) {
Phone phone = buy.get(i);
if (mList.get(buyId - 1).getName().equals(phone.name)) {
buyCount += phone.count;
buy.remove(phone);
isNewAdd = true;
}
}
//把买的东西加入到集合中
if (isNewAdd) {
buy.add(new Phone(mList.get(buyId - 1).getId(), mList.get(
buyId - 1).getName(), mList.get(buyId - 1).getPrice(),
buyCount));
}
System.out.println("是否继续,1:继续 0 退出");
iscontinue = mScanner.nextInt();
} while (iscontinue != 0);
System.out.println("你购买的商品为");
for (Phone phone : buy) {
System.out.println(phone);
}
mScanner.close();
}
}
其中不足的地方是最后打印buy这个集合不是按照id排列的可以从新集合的排序方式来实现(重写Comparator这个方法)
附:排序可以查看http://blog.csdn.net/dr_abandon/article/details/52577067