本文主要是介绍一个类有成员1与成员2,在集合中不断添加对象,对成员1去重,更新成员2(保持最大),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一个类有成员1与成员2,在集合中不断添加对象,对成员1去重,更新成员2(保持最大)
对于这个需求,之前我的想法是用HashSet做,并且重写类的equals与hashcode方法,让这个类在去重的时候只care成员1,然后HashSet如果contains这个对象,就去查找返回这个对象。
但是事实证明我想的不仅复杂,而且错了,到现在我都没能找到HashSet查找返回对象的方法。
听取了一个朋友的建议,我修改了策略,使用HashMap做这件事。用成员1作为key,对象作为value。
这里以学生类为例,维护名字的唯一性,不断使得年龄最大。
import java.util.*;class Student{String name;int age;public Student(String name, int age) {this.name = name;this.age = age;}
}public class Main {HashMap<String,Student> hashMap=new HashMap<>();void insertHashMap(Student student){if(hashMap.containsKey(student.name)){Student oldObj=hashMap.get(student.name);if(student.age>oldObj.age){System.out.println("update, new student "+student.name+" age is "+student.age+", greater than "+oldObj.age);hashMap.remove(student.name);hashMap.put(student.name,student);}elseSystem.out.println("ignore, new student "+student.name+" age is "+student.age+", less than "+oldObj.age);}else{hashMap.put(student.name, student);System.out.println("update, new student "+student.name+" age is "+student.age);}}void solve(){insertHashMap(new Student("tqc",22));insertHashMap(new Student("tqc",45));insertHashMap(new Student("dd",33));insertHashMap(new Student("dd",11));insertHashMap(new Student("ff",11));insertHashMap(new Student("ff",22));}public static void main(String[] args) {new Main().solve();}
}
结果
update, new student tqc age is 22
update, new student tqc age is 45, greater than 22
update, new student dd age is 33
ignore, new student dd age is 11, less than 33
update, new student ff age is 11
update, new student ff age is 22, greater than 11
这篇关于一个类有成员1与成员2,在集合中不断添加对象,对成员1去重,更新成员2(保持最大)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!