java list详解及arrayList的四种遍历方法

来源:互联网 发布:ubuntu 精简版 编辑:程序博客网 时间:2024/05/16 17:16


1.List接口提供的适合于自身的常用方法均与索引有关,这是因为List集合为列表类型,以线性方式存储对象,可以通过对象的索引操作对象。

  List接口的常用实现类有ArrayList和LinkedList,在使用List集合时,通常情况下声明为List类型,实例化时根据实际情况的需要,实例化为

  ArrayList或LinkedList,例如:List<String> l = new ArrayList<String&gt;();// 利用ArrayList类实例化List集合List<String> l2 = new LinkedList<String>();

  // 利用LinkedList类实例化List集合


2.add(int index, Object obj)方法和set(int index, Object obj)方法的区别在使用List集合时需要注意区分add(int index, Object obj)方法和set(int index, Object obj)方法,

     前者是向指定索引位置添加对象,而后者是修改指定索引位置的对象


3.indexOf(Object obj)方法和lastIndexOf(Object obj)方法的区别在使用List集合时需要注意区分indexOf(Object obj)方法和lastIndexOf(Object obj)方法,

   前者是获得指定对象的最小的索引位置,而后者是获得指定对象的最大的索引位置,前提条件是指定的对象在List集合中具有重复的对象,否则如果在List集合中

   有且仅有一个指定的对象,则通过这两个方法获得的索引位置是相同的


4 subList(int fromIndex, int toIndex)方法在使用subList(int fromIndex, int toIndex)方法截取现有List集合中的部分对象生成新的List集合时,需要注意的是,

    新生成的集合中包含起始索引位置代表的对象,但是不包含终止索引位置代表的对象



拓展:

  1. 通常用法:List<类型> list=new ArrayList<类型>();  
  2. List是一个接口,不可实例化,  
  3. 通过实例化其实现类来使用List集合,  
  4. 他的最常用实现类ArrayList;  
  5. 使用示例:List<String> list= new ArrayList<String>();   
  6.   
  7. List<T> list=new ArrayList<T>();  
  8. 其中类型T是对list集合元素类型的约束,  
  9. 比如说你声明了一个List<String>,  
  10. 然后往这个集合里面添加一个不是String类型的对象,  
  11. 会引发异常。 

遍历arrayList的四种方法

package com.test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ArrayListDemo {
    publicstatic void main(String args[]){
       List<String> list = newArrayList<String>();
       list.add("luojiahui");
       list.add("luojiafeng");

       //方法1
       Iterator it1 = list.iterator();
       while(it1.hasNext()){
           System.out.println(it1.next());
       }

       //方法2
       for(Iterator it2 = list.iterator();it2.hasNext();){
            System.out.println(it2.next());
       }

       //方法3
       for(String tmp:list){
           System.out.println(tmp);
       }

       //方法4
       for(int i = 0;i < list.size(); i ++){
           System.out.println(list.get(i));
       }

    }
}


0 0