有序的、可重复的数据
方法 | 描述 |
---|---|
add(Object) | 增加 |
remove(int index)/ remove(Object obj) | 删除 |
set(int index , object ele) | 修改 |
get(int index) | 查找 |
add(int index, Object ele) | 插入 |
size() | 长度 |
① Itertor 迭代器 ②foreach ③ for | 遍历 |
默认情况下:扩容为原来的 1.5 倍,同时需要将原有的数组中的数据复制到新的数组中。 结论:建议开发中使用带参的构造器:ArrayList list = new ArrayList(int capacity)
后续的添加和扩容与 jdk 7 无异。 结论:jdk 7 中的 ArrayList 的对象的创建类似于单例的饿汉式,而 jdk 8 中的 ArrayList 的对象的创建类似于单例模式的懒汉式延迟了数组的创建,节省了空间。
LinkedList 的源码分析
其中 Node 定义为:体现了 linkedList 的双向链表的说法
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;//前
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
Vector 的源码分析
添加对象,所在的类要重写 equals()方法
无序的,不可重复的元素
对于添加成功的情况 2 和情况 3 而言:元素 a 与已经存在指定索引上数据以链表的方式存储。 JDK 7 :元素 a 放大数组中,指向元素 a。 JDK 8 : 原来的元素在数组中,指向元素 a。 总结:七上八下 HashSet 底层:数组加链表的结构。(前提:jdk7)
set 接口没有定义新的方法,使用的都是 collection 声明方法。
public class User implements Comparable{
private String name;
private int age;
public User() {
}
public User(String name, int age) {
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 boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return age == user.age &&
name.equals(user.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Object o) {
if(o instanceof User){
User user = (User) o;
if(this.name.equals(user.name)){
return this.age - user.age;
}
return this.name.compareTo(user.name);
}
throw new RuntimeException("输入的值无法判断");
}
}
@Test
public void test1() {
TreeSet set = new TreeSet();
set.add(new User("hunan", 12));
set.add(new User("beijing", 12));
set.add(new User("hunan", 9));
set.add(new User("fujian", 15));
set.add(new User("lingxia", 18));
Iterator iterator = set.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
@Test
public void test2(){
Comparator com = new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof User && o2 instanceof User){
User user1 = (User) o1;
User user2 = (User) o2;
return Integer.compare(user1.getAge(), user2.getAge());
}else{
throw new RuntimeException("输入的数据类型不匹配");
}
}
};
TreeSet set = new TreeSet(com);
set.add(new User("Tom",12));
set.add(new User("Jerry",32));
set.add(new User("Jim",2));
set.add(new User("Mike",65));
set.add(new User("Mary",33));
set.add(new User("Jack",33));
set.add(new User("Jack",56));
Iterator iterator = set.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}