1集合容器中存数据,可以是字符串、整形、对象、集合、类等
/*
* List集合中可以放类对象
*/
package com.zkf.sb;
import java.util.ArrayList;
import java.util.List;
class Person{
private String name;
private int id;
public Person() {
}
public Person(String name, int id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Person [name=" + name + ", id=" + id + "]";
}
}
public class Demo1 {
public static void main(String[] args) {
List<Person> list = new ArrayList<Person>();
Person person1 = new Person("开放",45);
Person person2 = new Person("开放",34);
Person person3 = new Person("开放",45);
Person person4 = new Person("开放",45);
list.add(person1);
list.add(person2);
list.add(person3);
list.add(person4);
// System.out.println(list);
// System.out.println(list.get(0));
// System.out.println(list.get(1));
// System.out.println(list.get(2));
// System.out.println(list.get(3).getName());//单独取出来名字,不取id
for (Person person: list) {
System.out.println(person.getName() + ":" + person.getId());
}
}
}
2ArrayList源码
底层是数组,
默认容量是10,
当调用add方法的时候可能触发扩容
通过grow方法扩容,扩容后长度是原来的1.5倍
//int newCapacity = 10 + 10 / 2====> 15
// int newCapacity = oldCapacity + oldCapacity / 2;
3LinkedList
List是ListedList的父接口
LinkedList底层是链表
4ArrayList和LinkedList的区别
ArrayList底层是数组,LinkedList底层是链表
ArrayList在随机数据的效率高于LinkedList
ArrayList在插入、删除的效率低于LinkedList
LinkedList是存储数据节点的信息以及节点的内存地址