标签:style lis socket mamicode img ack util test color
/*
*
* 使用HashMap存储数据并遍历(字符串作为key)
*
*使用HashMap存储数据并遍历(自定义对象作为key)
*/
字符串做key和Map的使用一样,重点介绍自定义对象作为key
package day30_2_Map.hashmap; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /* * 使用HashMap存储数据并遍历(自定义对象作为key) */ public class HashMapDemo2 { public static void main(String[] args) { HashMap<Student,String> hm = new HashMap<>(); Student s = new Student("zhangsan",12); Student s2 = new Student("lisi",18); Student s3 = new Student("lisi",18); hm.put(s,"test001"); hm.put(s2,"test002"); hm.put(s3,"test002"); Set<Map.Entry<Student,String>> entry = hm.entrySet(); for (Map.Entry<Student,String> entrys : entry) { Student key = entrys.getKey(); String value = entrys.getValue(); System.out.println(key + "=" +value); } } }
package day30_2_Map.hashmap; import jdk.net.SocketFlow; import java.util.Objects; public class Student { String name; int age; public Student() { } public Student(String name,int age) { this.name = name; this.age = age; } @Override public String toString() { return "Student{" + "name=‘" + name + ‘\‘‘ + ", age=" + age + ‘}‘; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return age == student.age && Objects.equals(name, student.name); } @Override public int hashCode() { return Objects.hash(name, age); } }
输出
说明:
输出Student对象为地址值,需要重写其toString方法
作为key的Student对象未去重,需要重新equals和hashcode方法
标签:style lis socket mamicode img ack util test color
原文地址:https://www.cnblogs.com/longesang/p/11287795.html