- 红黑树与平衡二叉树的区别:
- 平衡二叉树高度平衡:当左右子树的高度相差大于1时,便会发生旋转
- 红黑树不是高度平衡:它有着自己的红黑规则
- 添加规则为,若添加三个元素,调整两次(默认颜色为黑色),当默认颜色为红色时只需调整一次,所以默认颜色为红色效率高
- HashSet集合(set的实现类之一)(哈希值)
- 特点:元素唯一、没有索引、不能使用普通fori循环、存取顺序不一致、底层结构哈希表
- 哈希值:jdk根据对象地址值或属性值计算出int类型整数
- object中hashcode()方法可以计算哈希值,即根据地址值进行计算,若要根据属性值进行计算,则需重写hashcode()方法
- HashSet集合储存数据流程:
- 1.计算出相应的哈希值 2.根据哈希值找出数组中相对应的位置 3.若为null则直接存入,反之进行判断调用equals方法判断属性值,若值一样则不存,反之存入数组,老元素挂在新元素下,以此类推.形成链表
- HashSet集合存自定义类必须重写hashcode和equals方法,即根据属性计算哈希值
- map:以键值对的形式储存,键唯一,值可重复
- map方法
public class Test06 {
public static void main(String[] args) {
Map<String ,Integer> map = new TreeMap<>();
map.put("昙花",10);
map.put("梅花",1);
map.put("玫瑰",2);
map.put("玫瑰",33);
System.out.println(map);
Integer remove = map.remove("昙花");
System.out.println(remove);
System.out.println(map);
map.clear();
System.out.println(map);
boolean key = map.containsKey("刺玫");
System.out.println(key);
boolean empty = map.isEmpty();
System.out.println(empty);
int size = map.size();
System.out.println(size);
}
}
public class Student {
private String anme;
private int age;
public Student() {
}
public Student(String anme, int age) {
this.anme = anme;
this.age = age;
}
public String getAnme() {
return anme;
}
public void setAnme(String anme) {
this.anme = anme;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"anme='" + anme + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age &&
Objects.equals(anme, student.anme);
}
@Override
public int hashCode() {
return Objects.hash(anme, age);
}
}
public class Test07 {
public static void main(String[] args) {
TreeMap<Student, String> map = new TreeMap<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int result = o1.getAge() - o2.getAge();
result= result==0? o1.getAnme().compareTo(o2.getAnme()):result;
return result;
}
});
Student s1 = new Student("吕布",33);
Student s2 = new Student("貂蝉",22);
Student s3 = new Student("曹操",44);
Student s4 = new Student("张飞",35);
map.put(s1,"方天画戟");
map.put(s2,"美如天仙");
map.put(s3,"老谋深算");
map.put(s4,"力大无穷");
Set<Student> keySet = map.keySet();
for (Student key : keySet) {
String value = map.get(key);
System.out.println("键为"+key+"值为"+value);
}
System.out.println("-------------------------------");
Set<Map.Entry<Student, String>> entries = map.entrySet();
for (Map.Entry<Student, String> entry : entries) {
Student key = entry.getKey();
String value = entry.getValue();
System.out.println("键为"+key+"值为"+value);
}
System.out.println("-------------------------------");
map.forEach(
(Student stu ,String str)->{
System.out.println("键为"+stu+"值为"+str);
}
);
}
}
- TreeMap集合(底层结构红黑树),使用自定义类时需进自然排序或比较器排序,使用方法跟TreeSet类似