List的运用

 1 package jihe;
 2 
 3 import java.util.*;
 4 
 5 public class Test1 {
 6 
 7     public static void main(String[] args) {
 8         // TODO Auto-generated method stub
 9         //创建List
10         //1.指明数据类型, 不需要指定大小
11         //<> 表示泛型
12         List<String>list=new ArrayList<String>();
13         
14         ArrayList<Object> list1=new ArrayList<Object>();
15         
16         list1.add(1);
17         
18         
19         
20         
21         
22         
23         //添加
24         list.add("a");
25         list.add("b");
26         list.add("c");
27         
28         //长度
29         System.out.println("List的长度="+list.size());
30         //取出
31         System.out.println("按索引取出get(0)="+list.get(0));
32         //遍历
33         System.out.println("遍历方式1");
34         for(int i=0;i<list.size();i++)
35         {
36             System.out.println(list.get(i));
37         }
38         
39         list.remove(0);
40         System.out.println("遍历方式2");
41         for(String s:list)
42         {
43             System.out.println(s);
44         }
45         System.out.println("遍历方式3");
46         //迭代器
47         //获取集合的迭代器,迭代器一开始是在集合的上面
48         Iterator<String> it=list.iterator();
49         //试探
50         while(it.hasNext())
51         {
52             String t=it.next();
53             if(t.equals("b"))
54             {
55                 it.remove();
56             }
57             System.out.println("迭代器="+t);
58         }
59         //移除
60         //list.clear();//全部移除
61         //list.remove(0);//移除指定的
62         System.out.println("移除后长度="+list.size());
63         //插入
64         list.add(0, "A");//在指定索引位置插入
65         
66         //修改
67         list.set(1, "B");//修改指定索引位置的值
68         //list.set(2, "c");
69                 
70         for(String s:list)
71         {
72             System.out.println(s);
73         }
74     
75         //查找List中元素的索引位置
76         System.out.println(list.indexOf("B"));
77         
78     }
79 
80 }
View Code

原文地址:https://www.cnblogs.com/beens/p/5261705.html