今天学习了Map集合。
Map是一种以键值对的形式存在的集合,其中每个键映射到一个值,几乎所有通用 Map 都使用哈希映射。位于java.util包中,其子类有HashMap,TreeMap。HashMap缺省的情况下是线程非安全的;当多线程访问时可能需要提供同步机制,key和value的值允许为null,键值允许重复,没有顺序。
对于map集合遍历元素的两种方式进行了练习,结果如下:
package com.itpractice;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class StudentMapDemo {
public static void main(String[] args) {
HashMap<Student, String> hm = new HashMap<Student, String>();
hm.put(new Student("jinglt", 27), "三河");
hm.put(new Student("yangq", 26), "临沂");
hm.put(new Student("liul", 25), "武汉");
hm.put(new Student("jinglt", 24), "三河");
// 第一种取出方式:keySet()
// Set<Student> keySet = hm.keySet();
Iterator<Student> it1 = hm.keySet().iterator();
while (it1.hasNext()) {
Student s = it1.next();
System.out.println("学生姓名:" + s.getName() + " *** " + "学生年龄:"
+ s.getAge() + " *** " + "学生地址:" + hm.get(s));
}
System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
// 第二种取出方式:entrySet()
//Set<Map.Entry<Student, String>> entrySet = hm.entrySet();
Iterator<Map.Entry<Student, String>> it2 = hm.entrySet().iterator();
while (it2.hasNext()) {
Map.Entry<Student, String> me = it2.next();
System.out.println("学生姓名:" + me.getKey().getName() + "---"
+ "学生年龄:" + me.getKey().getAge() + "---" + "学生地址:"
+ me.getValue());
}
}
}
/**
* 定义一个学生类
*
* @author Administrator
*
*/
class Student implements Comparable<Student> {
/**
* 学生姓名
*/
private String name;
/**
* 学生年龄
*/
private int age;
/**
* 无参构造函数
*/
public Student() {
super();
}
/**
* 构造函数
*/
public Student(String name, int age) {
this.name = name;
this.age = age;
}
/**
* getXxx()和setXxx()方法
*/
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;
}
/**
* 重写toString()方法
*/
@Override
public String toString() {
return "student [name=" + name + ", age=" + age + "]";
}
/**
* 重写hashCode()方法
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
/**
* 重写equals()方法
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
/**
* 覆盖父类的compareTo()方法
*/
@Override
public int compareTo(Student s) {
int num = new Integer(this.age).compareTo(s.age);
if (num == 0)
return this.name.compareTo(s.name);
return num;
}
}