我是靠谱客的博主 高大小伙,这篇文章主要介绍HashMap存储自定义对象练习(两种取出方式),现在分享给大家,希望可以做个参考。

#日常练习

使用HashMap存储自定义对象,熟悉KeySet,EntrySet两种取出方式,定义自定义类是在不知道存储在哪种结构中时

建议复写hashCode,equals等方法,实现Comparable接口。


复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package Map; import java.util.*; import java.util.Map.Entry; /* * 要求:用HashMap存储自定义对象,并采用两种方法取出 * 思路:创建自定义对象(考虑到可能存储到其他类型的集合中, * 在创建时需要复写hashCode,equals方法,实现Comparator接口) * 使用KeySet,EntrySet取出元素; * */ //实现的应该是Comparable,而不是Comparetor, //后者是比较器通常用于在调用的类内没有比较方法或方法不符合要求时自定义比较器 //并将其作为参数传入集合来完成特定比较 public class HashMapTest { public static void main(String[] args) { HashMap<Student,String> hm = new HashMap<Student,String>(); hm.put(new Student("student1",21), "beijing"); hm.put(new Student("student2",22), "shanghai"); hm.put(new Student("student3",23), "anhui"); hm.put(new Student("student4",24), "anhui"); //取出 //KeySet取出 Set<Student> keySet = hm.keySet(); for(Iterator<Student> it = keySet.iterator();it.hasNext();) { Student s = it.next(); System.out.println(s.getName()+" "+s.getAge()+" "+hm.get(s)); } //EntrySet Set<Entry<Student,String>> entrySet = hm.entrySet(); for(Iterator<Entry<Student,String>> iter = entrySet.iterator();iter.hasNext();) { Entry<Student,String> en = iter.next(); Student s = en.getKey(); String address = en.getValue(); System.out.println(s.getName()+"----"+s.getAge()+"-----"+address); } } }

被调用的类
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Student implements Comparable<Student>{ private String name; private int age; 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; } public int compareTo(Student s) { int num = new Integer(this.age).compareTo(new Integer(s.age)); if(num == 0) { return this.name.compareTo(s.name); } return num; } public int hashCode(Object obj) { return name.hashCode()+age*32; } public boolean equals(Object obj) { if(!(obj instanceof Student)) throw new ClassCastException("传入的类类型异常"); Student s = (Student)obj; if(this.age == s.age && this.name.equals(s.name)) return true; return false; } }



最后

以上就是高大小伙最近收集整理的关于HashMap存储自定义对象练习(两种取出方式)的全部内容,更多相关HashMap存储自定义对象练习(两种取出方式)内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(48)

评论列表共有 0 条评论

立即
投稿
返回
顶部