arraylist linkedlist
hashset linkedhasset treeset
arraylist linkedlist
线程 不 安全
数组 链表
0.5倍扩容 不
查询 增删
vector 效率低 就不用了
iterator
boolean hasNext() 和 Iterator<E> iterator()
Collection<String> collection = new ArrayList<>();
collection.add("余华1");
collection.add("余华4");
collection.add("余华100");
collection.add("余华2");
//iterator.next() 只可以用一次
Iterator<String> iterator = collection.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
for (String s : collection) {
System.out.println(s);
}
collection.forEach((s) -> {
System.out.println(s);
});
哈希表(Hash Table):也叫做散列表。是根据关键码值(Key Value)直接进行访问的数据结构。
哈希表通过「键 key 」和「映射函数 Hash(key) 」计算出对应的「值 value」,把关键码值映射到表中一个位置来访问记录,以加快查找的速度。这个映射函数叫做「哈希函数(散列函数)」,存放记录的数组叫做「哈希表(散列表)」。
set集合
Set系列集合的特点。 无序、不重复、无索引。 Set集合的实现类特点。
HashSet无序、不重复、无索引。
LinkedHashSet 有序、不重复、无索引。
TreeSet 可排序、不重复、无索引。
HashSet集合元素无序的底层原理:哈希表
LinkedHashSet 底层数据结构是依然哈希表,只是每个元素又额外的多了一个双链表的机制记录存储的顺序。
TreeSet集合底层是基于红黑树的数据结构实现排序的,增删改查性能都较好。
//批量添加 打乱List集合元素的顺序
List<String> collection = new ArrayList<>();
// collection.add("余华1");
// collection.add("余华4");
// collection.add("余华100");
// collection.add("余华2");
//批量添加
Collections.addAll(collection, "余华1","余华4","余华100","余华2");
//因为shuffle 的参数 是list 集合 所以要写为list
Collections.shuffle(collection);
TreeMap集合自定义排序规则有2种
1.类实现Comparable接口,重写比较规则。
2.集合自定义Comparator比较器对象,重写比较规则。
1.NewStudent类:
public class NewStudent implements Comparable<NewStudent> {
public Integer age;
public String name;
public Integer sex;
public NewStudent() {
}
public NewStudent(Integer age, String name, Integer sex) {
this.age = age;
this.name = name;
this.sex = sex;
}
@Override
public String toString() {
return "NewStudent{" +
"age=" + age +
", name='" + name + '\'' +
", sex=" + sex +
'}';
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
@Override
public int compareTo(NewStudent o) {
return this.age - o.age;
}
}
Test:
Map<NewStudent, String> map = new TreeMap();
map.put(new NewStudent(15,"数学课",1),"123");
map.put(new NewStudent(18,"语文课",2),"456");
map.put(new NewStudent(15,"英语课",1),"789");
System.out.println(map);
结果:
{NewStudent{age=15, name='数学课', sex=1}=789, NewStudent{age=18, name='语文课', sex=2}=456}
2.集合自定义Comparator比较器对象,重写比较规则。
Map<NewStudent, String> map = new TreeMap<>(Comparator.comparing(NewStudent::getAge));
map.put(new NewStudent(15,"数学课",1),"123");
map.put(new NewStudent(18,"语文课",2),"456");
map.put(new NewStudent(15,"英语课",1),"789");
System.out.println(map);