java數組求和
發布時間: 2024-01-12 20:03:57
1. java中如何把2個LIST相同的內容相加
packagetest;
importjava.util.*;
publicclassTest{
publicvoidtest(){
Listlist1=newArrayList();
list1.add(newField("A",1));
list1.add(newField("B",1));
list1.add(newField("C",1));
Listlist2=newArrayList();
list2.add(newField("A",2));
list2.add(newField("D",2));
list2.add(newField("E",2));
Listres=Join(list1,list2);
for(Fieldfield:res){
System.out.print(field.getName()+":"+field.getValue()+",");
}
}
publicstaticvoidmain(String[]args){
newTest().test();
}
publicstaticListJoin(Listlist1,Listlist2){
Listres=newArrayList();
Listlist2_=newArrayList(list2);
for(Fieldfield1:list1){
booleanhasSameOne=false;
for(Fieldfield2:list2){
if(field1.getName().equals(field2.getName())){
res.add(field1.add(field2));
list2_.remove(field2);
hasSameOne=true;
}
}
if(!hasSameOne)
res.add(field1);
}
res.addAll(list2_);
returnres;
}
publicclassField{
privateintvalue=0;
privateStringname;
publicField(Stringname,intvalue){
this.name=name;
this.value=value;
}
publicintgetValue(){
returnvalue;
}
publicStringgetName(){
returnname;
}
publicFieldadd(Fieldvalue){
returnnewField(this.getName(),this.getValue()+value.getValue());
}
}
}
熱點內容