更新時間:2022-01-05 10:28:49 來源:動力節點 瀏覽1568次
1.map集合需要鍵名唯一,hashmap是通過hashcode和eauals來控制鍵名唯一;
2.從寫Comparable中的compareTo方法來對map集合排序;
實體類:
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Student s) {
int num = new Integer(this.getAge()).compareTo(new Integer(s.getAge()));
if (num == 0) {
num = this.getName().compareTo(s.getName());
}
return num;
}
@Override
public int hashCode() {
System.out.println(this.name+".....hashCode");
return this.getName().hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Student)) return false;
Student s = (Student) obj;
System.out.println(this.name+this.age+"..equals..");
return this.getName().equals(s.getName()) && this.getAge() == s.getAge();
}
}
測試類;
public class Test {
public static void main(String[] args) {
Map<Student, String> ms = new HashMap<Student, String>();
ms.put(new Student("張三", 10), "北京");
ms.put(new Student("張五", 12), "南京");
ms.put(new Student("張五", 12), "北京");
ms.put(new Student("張五", 13), "北京");
Set<Map.Entry<Student, String>> entries = ms.entrySet();
for (Iterator<Map.Entry<Student, String>> it2 = entries.iterator(); it2.hasNext(); ) {
Map.Entry<Student, String> next = it2.next();
System.out.println(next.getKey() + "====" + next.getValue());
}
}
}
以上就是HashMap去重和排序的方法,大家如果對此比較感興趣,想了解更多相關知識,不妨來關注一下動力節點的Java基礎教程,里面的課程內容豐富,由淺到深,通俗易懂,適合沒有基礎的小白學習,希望對大家能夠有所幫助。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習