Map练习(基本自定义类型练习)
来源:互联网 发布:java io 装饰器模式 编辑:程序博客网 时间:2024/03/28 17:28
package map;
import java.util.*;
public class MapDemo3 {
/**
* @Map练习
* 每一个学生都有对应的归属地。
* 学生Student,地址String。
* 学生属性:姓名,年龄
* 注意,姓名和年龄相同视为同一个学生
* 保证学生的唯一性。
*
*
* 1.描述学生。
*
* 2.定义map容器,将学生视作键,地址为值,存入。
*
* 3.获取map集合中的元素。
*/
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("lisi1",21),"tianjing");
hm.put(new Student("lisi2",22),"shanghai");
hm.put(new Student("lisi3",23),"nanjng");
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);
}
}
}
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 eauqls(Object obj){
if(!(obj instanceof Student))//如果传进来的不是Student 类型,返回异常
throw new ClassCastException("类型不匹配!!!");
Student s = (Student) obj;
System.out.println(this.name+"比较"+s.name);
return this.name.equals(s.name) && this.age == s.age;
}
public String toString(){
return name+"::"+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;
}
}
- Map练习(基本自定义类型练习)
- Map练习!!!
- Map练习
- Map练习
- C++语言之基本内置类型练习
- POJ 2418 Hardwood Species (map练习)
- NYOJ 95 众数问题(map练习)
- 比较器练习(list,set,map...)
- Map容器练习
- java Map练习(一)
- Map练习(二)
- java map练习
- java Map集合练习
- 集合(Map练习)
- C++ map练习
- hdu2643 map练习
- map集合练习
- 1075 MAP练习
- Map集合的基本操作
- POJ_2151_Check the difficulty of problems_概率DP
- Map集合的两种取出方式
- Linux GPIO操作分析 - Exynos 5260
- OV手机无线快门测评
- Map练习(基本自定义类型练习)
- 对于form.show() 和Application.run(form)的理解
- 1002
- TreeMap练习:对学生对象的姓名进行升序排序
- 程序员面试金典(1) 字符串是否所有字符不同
- Java 中的equals
- Android studio 导入github工程
- 关于Executor 接口
- TreeMap基本练习:获取某字符串中的字母出现的次数