如题:把List1中的数据入库到List2中,假设包含两个元素,商品名和商品数量
规则:List2中已存在你的商品,直接修改数量;List2中不存在的商品,把List1中的直接复制到List2
在论坛上看了这道题,就跟着楼主的思路走了:先把List1中的商品按同种类的统计出来,然后再合并到List2中,
然后写了很多的代码,最后回到论坛一看,,,直接把List1逐一合并到List2 中不就行了吗??何必多此一举呢,
这样代码还能节省好多。
以后要自己动脑,先考虑好了再下手,不然就会走岔路了,吃力不讨好
import java.util.ArrayList;
import java.util.List;
/**
* 把a1中的数据合并到a2中
* a2中已存在相同name的数据,合并数量,不存在相同name的数据,把a1中的数据复制到a2中
* @author yuxiang0728
*
*/
class Product2 {
protected String item_name;
protected int num;
public Product2() {}
public Product2(String na, int num) {
this.item_name = na;
this.num = num;
}
public String show() {
return ("商品名称 :" + this.item_name + "\t数量:" + this.num + "\r\n");
}
}
public class Product_in2 extends Product2 {
private String item_person;
public Product_in2(String name, String Person, int num) {
this.item_name = name;
this.item_person = Person;
this.num = num;
}
public String getItem_person() {
return item_person;
}
public void setItem_person(String item_person) {
this.item_person = item_person;
}
public String show() {
return ("商品名称 :" + this.item_name + "\t数量:" + this.num + "\t操作人 :"
+ this.item_person + "\r\n");
}
public static void main(String[] args) {
transInfo();
}
public static void transInfo() {// 给a2归类存在问题
List<Product_in2> a1=new ArrayList<Product_in2>(); //a1的定义
a1.add(new Product_in2("商品A","test",3));
a1.add(new Product_in2("商品A","test",4));
a1.add(new Product_in2("商品A","test",7));
a1.add(new Product_in2("商品B","test",5));
a1.add(new Product_in2("商品B","test",8));
a1.add(new Product_in2("商品C","test",6));
List<Product2> a2 = new ArrayList<Product2>();//a2的定义
a2.add(new Product2("商品R",1));
a2.add(new Product2("商品A",1));
System.out.println("-------------初始-a1-------------------");
for (int i = 0; i < a1.size(); i++) {
System.out.println(a1.get(i).show());
}
System.out.println("-------------初始-a2------------------");
for (int i = 0; i < a2.size(); i++) {
System.out.println(a2.get(i).show());
}
for (int i = 0; i < a1.size(); i++) {
boolean flag = false;
for (int j = 0; j < a2.size(); j++) {
if(a2.get(j).item_name.equals(a1.get(i).item_name)){
a2.get(j).num += a1.get(i).num;
flag = true;
break;
}
}
if(!flag){
a2.add(new Product2(a1.get(i).item_name,a1.get(i).num));
}
}
System.out.println("-------------合并 a1——>a2 ------------------");
for (int i = 0; i < a2.size(); i++) {
System.out.println(a2.get(i).show());
}
}
}