LinkedList底层使用数组存储数据,数据结构是链表
链表相较于数组的优点:添加和删除时更加便捷,改变指针指向就行,不需要挪动位置
缺点:内存空间占用更大
添加数据add
package List;
import java.util.LinkedList;
public class linkedList {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add("zhangsan");
System.out.println(list);//[zhangsan]
System.out.println(list.getFirst());//zhangsan
System.out.println(list.getLast());//zhangsan
}
}
添加第二个数据
package List;
import java.util.LinkedList;
public class linkedList {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add("zhangsan");
System.out.println(list);//[zhangsan]
// list.add("lisi");//默认在后面加
// System.out.println(list);//[zhangsan, lisi]
list.addFirst("lisi");//在前面加
System.out.println(list);//[lisi, zhangsan]
System.out.println(list.getFirst());//lisi
System.out.println(list.getLast());//zhangsan
}
}
添加第三个数据
package List;
import java.util.LinkedList;
public class linkedList {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add("zhangsan");
list.addFirst("lisi");//在前面加
// list.addFirst("wangwu");//在最前面加
// System.out.println(list);//[wangwu, lisi, zhangsan]
list.add(1,"wangwu");//根据索引添加
System.out.println(list);//[lisi, wangwu, zhangsan]
System.out.println(list.getFirst());//lisi
System.out.println(list.getLast());//zhangsan
}
}
添加前后的索引变化,链表是没有索引的,java会根据数据的位置来构建索引
还有addAll,和ArrayList一样
获取数据get
package List;
import java.util.LinkedList;
public class linkedList {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add("zhangsan");
list.addFirst("lisi");//在前面加
list.add(1,"wangwu");//根据索引添加
System.out.println(list);//[lisi, wangwu, zhangsan]
System.out.println(list.get(1));//根据索引获取数据,wangwu
System.out.println(list.getFirst());//获取第一个数据,lisi
System.out.println(list.getLast());//获取最后一个数据,zhangsan
//遍历
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
System.out.println("---------------------------------");
for (Object obj:list ){
System.out.println(obj);
}
}
}
修改set
package List;
import java.util.LinkedList;
public class linkedList {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add("zhangsan");
list.addFirst("lisi");//在前面加
list.add(1,"wangwu");//根据索引添加
System.out.println(list);//[lisi, wangwu, zhangsan]
list.set(1,"zhaoliu");
System.out.println(list);//[lisi, zhaoliu, zhangsan]
}
}
删除remove
package List;
import java.util.LinkedList;
public class linkedList {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add("zhangsan");
list.addFirst("lisi");//在前面加
list.add(1,"wangwu");//根据索引添加
System.out.println(list);//[lisi, wangwu, zhangsan]
list.remove("wangwu");
System.out.println(list);//[lisi, zhangsan]
}
}
list.remove()和list.removeFirst都是删除第一个数据
其他方法
push和addFirst一样都是在第一个位置添加数据
pop和removeFirst一样都是在第一个位置删除数据