Java入门15 -- Tree
Map 实现年级班级学生表
Student.java
public class Student {
private int age;
private int height;
private int weight;
public Student( int height, int weight,int age) {
this.age = age;
this.height = height;
this.weight = weight;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
@Override
public int hashCode() {
return this.height | this.weight << 8 | this.age << 16;
}
public boolean equals(Object obj){
if(obj == null) return false;
if(obj == this) return true;
if(obj instanceof Student){
return this.hashCode() == obj.hashCode();
}
return false;
}
}
MapNesteDemo.java
import java.util.HashMap;
import java.util.Map;
public class MapNesteDemo {
public static void main(String[] args) {
//学生集合
Map<String,String> names = null;
//班级集合
Map<String,Map<String,String>> classes = null;
//初始化年级集合
Map<String,Map<String,Map<String,String>>> grades = new HashMap<String, Map<String, Map<String, String>>>();
for(int i = 1 ; i <= 3 ; i ++){
classes = new HashMap<String, Map<String, String>>();
grades.put(i + "年级",classes);
for(int j = 1; j <= 2; j ++){
//创建名单集合----一个班
names = new HashMap<String, String>();
classes.put (i +"年级"+ j + "班" , names);
for(int k = 1; k <= 5 ; k++){
names.put("No" + i + "-" + j + "-" + k,"tom" +(k ++));
}
}
}
//迭代输出
for(Map.Entry<String,Map<String,Map<String,String>>> entry:grades.entrySet()){
//年级名称
String key = entry.getKey();
//班级集合
Map<String,Map<String,String>> classes0 = entry.getValue();
//先输出年级名称
System.out.println(key);
//年级内的每个班
for(Map.Entry<String,Map<String,String>> e:classes0.entrySet()) {
//班级名称
String className = e.getKey();
//名单集合
Map<String, String> v = e.getValue();
System.out.println("\t" + className);
//名单集合
for(Map.Entry<String,String> e2 : v.entrySet()) {
String stuNo = e2.getKey();
String stuName = e2.getValue();
System.out.println("\t\t" + stuNo + " - " + stuName);
}
}
}
}
}
集合框架中常用的接口
Collection接口中有两个子接口
List
可以存放重复元素,元素的存放是有序的
Set
不可以存放重复的元素,元素的存放是无序的
先判断Hashcode 是否相同,如果不同,可以存放,如果相同,再判断是否是同一个对象==
若是同一个对象,视为重复,
在判断equals方法是否相同
this,hash == obj,hash && (this == pbj || this.equals(obj))
List接口中常用的类
Vector 向量
线程安全,但是速度慢,被ArrayList替代
ArrayList
线程不安全,查询速度快
LinkedList
链表结构,增删速度快
取出List集合中的方式
get(int index ):脚标获取元素
iterator():迭代方法获取迭代对象
Set
Hashset,底层用的就是hashmap
Map
Hashmap
Set接口中常用的类
HashSet
线程不安全,存取速度快
Set集合元素唯一性原因
HashSet:通过hashCode()方法 == equals()方法来保证元素是否相同
TreeSet
通过compare To 或者compare方法中的来保证元素的唯一性,
元素是以二叉树存放的