Java的集合

1.ArrayList

ArrayList集合类

构造方法

说明

public ArrayList() 构造一个初始容量为10的空列表

1.1.增加元素

ArrayList集合类

成员方法

说明

 public boolean add(E e)  将指定的元素添加到此列表的尾部
 public void add(int index, E element)  在指定索引处添加元素,之前元素一并右移

   定义一个ArrayList类,添加元素:

1 ArrayList<String> al = new ArrayList<String>();
2 al.add("hello");                               
3 al.add(0, "world");                            
4                                                
5 System.out.println(al); // [world, hello]      

  指定索引时,索引越界异常:(指定的索引在集合中不存在)

al.add(7, "USA");                        
System.out.println(al);

1.2.删、改、查

 

类型

成员方法

说明

 public E get(int index) 返回列表中指定位置上的元素(存在索引越界风险)
 public int size() 返回集合中元素的个数
 public int indexOf(Object o) 返回列表集合中首次出现指定元素的索引(没有返回-1)
 public boolean isEmpty() 无元素,返回true
 public E remove(int index) 删除指定位置的元素;返回值是被删除元素
 public boolean remove(Object o) 移除首次出现的该元素;包含元素返回true
 public E set(int index, E element) 用元素替代指定索引的内容;返回被替换的旧元素

1.3.遍历集合ArrayList

  通过ArrlyList集合的size、get方法实现遍历

1 //Sony                                                  
2 //said                                                  
3 //hello                                                 
4 //JavaEE                                                
5 for (int i = 0; i < al.size(); i++) {                   
6     System.out.println(al.get(i));                      
7 }                                                       
8 System.out.println(al); //[Sony, said, hello, JavaEE, .]

猜你喜欢

转载自www.cnblogs.com/argor/p/8960875.html