學習筆記
/**
* * A:案例演示
* 集合嵌套之HashMap嵌套HashMap
*
* 需求:
* 雙元課堂有很多基礎班
* 第88期基礎班定義成一個雙列集合,鍵是學生對象,值是學生的歸屬地
* 第99期基礎班定義成一個雙列集合,鍵是學生對象,值是學生的歸屬地
*
* 無論88期還是99期都是班級對象,所以爲了便於統一管理,把這些班級對象添加到雙元課堂集合中
*/
public static void main(String[] args) {
//定義88期基礎班
HashMap<Student, String> hm88 = new HashMap<>();
hm88.put(new Student("張三", 23), "北京");
hm88.put(new Student("李四", 24), "北京");
hm88.put(new Student("王五", 25), "上海");
hm88.put(new Student("趙六", 26), "廣州");
//定義99期基礎班
HashMap<Student, String> hm99 = new HashMap<>();
hm99.put(new Student("年輕帶", 1023), "北京");
hm99.put(new Student("老年代",1024), "北京");
hm99.put(new Student("持久帶",1025), "上海");
hm99.put(new Student("伊甸園",1026), "廣州");
//定義雙元課堂
HashMap<HashMap<Student, String>, String> hm = new HashMap<>();
hm.put(hm88, "jvm區域");
hm.put(hm99, "java學院區");
//遍歷雙列集合
for(HashMap<Student, String> h : hm.keySet()) { //hm.keySet()代表的是雙列集合中鍵的集合
String value = hm.get(h); //get(h)根據鍵對象獲取值對象
//遍歷鍵的雙列集合對象
for(Student key : h.keySet()) { //h.keySet()獲取集合總所有的學生鍵對象
String value2 = h.get(key);
System.out.println(key + "=" + value2 + "=" + value);
}
}
}
bean對象
public class Student implements Comparable<Student> {
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
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;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
@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;
}
@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;
}
@Override
public int compareTo(Student o) {
int num = this.age - o.age; //以年齡爲主要條件
return num == 0 ? this.name.compareTo(o.name) : num;
}
}