一、特点、特有方法
java
import java.util.ArrayList;
import java.util.List;
public class ListTest1 {
public static void main(String[] args) {
//1.创建一个ArrayList集合对象(有序,可重复,有索引)
List<String> list=new ArrayList<> ();
list.add ( "蜘蛛精" );
list.add ( "至尊宝" );
list.add ( "至尊宝" );
list.add ( "牛夫人" );
System.out.println (list);
//2.public void add(int index ,E element) :在某个索引处插入元素
list.add ( 2,"紫霞仙子" );
System.out.println ( list );
//3.public E remove(int index) 根据索引删除元素 返回被删除元素
System.out.println ( list.remove ( 2 ) );
System.out.println ( list );
//4.public E get(int index):返回集合中制定位置的元素
System.out.println ( list.get ( 3 ) );
//5.public E set(int index,E element):修改索引位置处的元素,修改成功后,会返回原来的数据
System.out.println ( list.set ( 3, "牛魔王" ) );
System.out.println ( list );
}
}
二、遍历方式(List家族通用)
java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ListTest2 {
public static void main(String[] args) {
List<String> list =new ArrayList<> ();
list.add ( "糖宝宝" );
list.add ( "王慧饭" );
list.add ( "大宝贝" );
//1.for 循环
for (int i = 0; i < list.size (); i++) {
String s = list.get ( i );
System.out.println ( s );
}
//2.迭代器
Iterator<String> id = list.iterator ();
while (id.hasNext ()){
System.out.println ( id.next () );
}
//3.foreach
for (String s : list) {
System.out.println (s);
}
//4.lambda表达式
list.forEach ( s -> System.out.println (s) );
}
}
三、ArrayList集合的底层原理,适用场景
四、LinkedList集合的底层原理(双链表)
1.底层原理
2.应用场景
1.排队
2.设计栈
java
import java.util.LinkedList;
public class ListTest3 {
public static void main(String[] args) {
//1.创建一个队列
LinkedList<String> queue=new LinkedList<> ();
queue.addLast ( "第1号人" );
queue.addLast ( "第2号人" );
queue.addLast ( "第3号人" );
queue.addLast ( "第4号人" );
System.out.println ( queue );
//出队操作
System.out.println ( queue.removeFirst () );
System.out.println ( queue.removeFirst () );
System.out.println ( queue.removeFirst () );
System.out.println ( queue );
System.out.println ("------------------------------");
//2.创建一个栈对象
LinkedList<String> stack=new LinkedList<> ();
//压入子弹(入栈)push
stack.addFirst ( "第1颗子弹" );
stack.addFirst ( "第2颗子弹" );
stack.addFirst ( "第3颗子弹" );
stack.addFirst ( "第4颗子弹" );
stack.push ( "第5课子弹" );//给addFirst换了个马甲
System.out.println (stack);
//发射子弹(出栈)pop
System.out.println ( stack.removeFirst () );
System.out.println ( stack.removeFirst () );
System.out.println ( stack.removeFirst () );
System.out.println ( stack.pop () );//给removeFirst换了个马甲
System.out.println ( stack );
}
}