本帖最后由 樊自超 于 2016-4-17 21:37 编辑
提到集合,最让我们头疼要数HashMap和TreeMap了.
以下是我个人的课堂总结,哈哈~
HashMap(☆☆☆):键是如何保证唯一性的呢? 通过哈希算法。 HashSet底层就是通过HashMap的键来完成的
所以说HashMap保证键的唯一性 必须要让键的元素所在的类去重写 hashCode()和 equals()方法
代码演示:
public static void main(String[] args) {
HashMap<Student, String> hm = new HashMap<>();
hm.put(new Student("张三", 23), "北京"); //Student作为键,必须重写equals和hashCode() 才能让HashMap保证键的唯一
hm.put(new Student("张三", 23), "上海");
hm.put(new Student("李四", 24), "广州");
hm.put(new Student("王五", 25), "深圳");
System.out.println(hm); //{Student [name=张三, age=23]=上海, Student [name=李四, age=24]=广州, Student [name=王五, age=25]=深圳} 去掉了重复的 "张三", 23
}
public class Student{ //重写了equals和HashCode的 Student类
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
@Override
public int hashCode() { //重写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) { //重写equals方法
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;
}
}
还有
TreeMap(☆☆☆):键是如何保证排序和唯一的呢?通过二叉树算法,TreeSet的底层就是通过TreeMap的键来完成的
方式一:所以TreeMap保证键的唯一和排序需要让 TreeMap的键的元素所在的类 去实现自然排序Comparable接口
方式二:TreeMap保证键的唯一和排序 需要调用TreeMap的有参构造,传入一个比较器 Comparator
代码演示:
public static void main(String[] args) {
TreeMap<Student, String> tm = new TreeMap<>(new Comparator<Student>() { //用TreeMap的有参构造方法 传入比较器
@Override
public int compare(Student s1, Student s2) {
int num = s1.getName().compareTo(s2.getName()); //按照姓名比较
return num == 0 ? s1.getAge() - s2.getAge() : num;
}
});
tm.put(new Student("张三", 23), "北京");
tm.put(new Student("李四", 13), "上海");
tm.put(new Student("赵六", 43), "深圳");
tm.put(new Student("王五", 33), "广州");
System.out.println(tm);
}
public static void demo1() {
TreeMap<Student, String> tm = new TreeMap<>(); //用TreeMap的无参构造方法创建的对象
tm.put(new Student("张三", 23), "北京"); //Student作为键,必须让Student实现Comparable接口 并且重写CompareTo方法
tm.put(new Student("李四", 13), "上海");
tm.put(new Student("王五", 33), "广州");
tm.put(new Student("赵六", 43), "深圳");
System.out.println(tm);
}
public class Student implements Comparable<Student> { //Student实现了Comparable接口 重写了CompareTo方法
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public int compareTo(Student o) { // 重写了CompareTo方法
int num = this.age - o.age; //以年龄为主要条件
return num == 0 ? this.name.compareTo(o.name) : num;
}
}
大家要多多总结,好好加油!方能立于不败之地啊! |
|