集合(Map练习)
来源:互联网 发布:知识产权 淘宝 编辑:程序博客网 时间:2024/04/23 21:55
每一个学生都有对应的归属地。
学生Student,地址:String。
学生属性:姓名,年龄
注意:姓名和年龄相同的视为同一个学生。
保证学生的唯一性。
1,描述学生。
2,定义map容器。将学生作为键,地址作为值,存入
3,获取map集合中的元素
import java.util.*;class Student implements Comparable<Student>{ private String name; private int age; Student(String name,int age) { this.name = name; 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() { return name.hashCode()+age*34; } public boolean equals(Object obj) { if(!(obj instanceof Student)) throw new ClassCastException("类型不匹配"); Student s = (Student)obj; return this.name.equals(s.name) && this.age==s.age; } public String getName() { return name; } public int getAge() { return age; } public String toString() { return name+":"+age; }} class MapTest{ public static void main(String[] args) { HashMap<Student,String> hm = new HashMap<Student,String>(); hm.put(new Student("lisi1",21),"beijing"); hm.put(new Student("lisi2",22),"shanghai"); hm.put(new Student("lisi3",23),"nanjing"); hm.put(new Student("lisi4",24),"wuhan"); //第一种取出方式 keySet Set<Student> keySet = hm.keySet(); Iterator<Student> it = keySet.iterator(); while(it.hasNext()) { Student stu = it.next(); String addr = hm.get(stu); System.out.println(stu+".."+addr); } //第二种取出方式 entrySet Set<Map.Entry<Student,String>> entrySet = hm.entrySet(); Iterator<Map.Entry<Student,String>> iter = entrySet.iterator(); while(iter.hasNext()) { Map.Entry<Student,String> me = iter.next(); Student stu = me.getKey(); String addr = me.getValue(); System.out.println(stu+"........."+addr); } }}
0 0
- java Map集合练习
- 集合(Map练习)
- map集合练习
- Map集合练习
- [黑马程序员]集合map练习
- 《黑马程序员》 map集合练习
- JAVA的map集合练习
- Practice Every Day_17(Map集合小练习)
- 19-Map集合-12-常用对象API(集合框架-Map集合练习-Map查表法)
- 集合框架--Map集合之记录字母次数练习
- 19-Map集合-10-常用对象API(集合框架-Map集合练习-记录字母次数思路)
- 19-Map集合-11-常用对象API(集合框架-Map集合练习-记录字母次数代码)
- map集合练习——记录字母次数
- Map练习!!!
- Map练习
- Map练习
- java集合框架的练习之Map集合以及其内部接口Entry的应用
- Map 集合
- Pat(Advanced Level)Practice--1081(Rational Sum)
- leetcode做题总结,题目Best Time to Buy and Sell Stock 2012/10/30
- 设计模式-适配器(Adaper)模式
- 关于dup和dup2函数的重定向与还原
- HDU 2163 Palindromes
- 集合(Map练习)
- 最短路径Ⅰ—Dijkstra算法
- Java多态
- JSP基础语法(章节摘要)
- 1407282112-hd-Max Num.cpp
- 集合(TreeMap练习)
- poj 2531
- C++与C添加标准库头文件的形式
- Jquery 分页