- import java.util.ArrayList;
- import java.util.List;
-
- public class ListTest1 {
- public static void main(String[] args) {
- //1.创建一个ArrayList集合对象(有序,可重复,有索引)
- List
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 );
- }
- }
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
-
- public class ListTest2 {
- public static void main(String[] args) {
- List
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
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) );
- }
- }
- import java.util.LinkedList;
-
- public class ListTest3 {
- public static void main(String[] args) {
- //1.创建一个队列
- LinkedList
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
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 );
-
-
- }
- }