Java_LIST使用方法和四种遍历arrayList方法

时间:2023-03-08 22:23:11

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集合,  他的最常用实现类ArrayList;  

  使用示例:List<String> list= new ArrayList<String>();   <数据类型string或者int或者boolen>表示泛型编程;

                 List<T> list=new ArrayList<T>();  其中类型T是对list集合元素类型的约束,  

                 比如说你声明了一个List<String>,然后往这个集合里面添加一个不是String类型的对象,会引发异常。 

遍历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 原理和方法1一样的
for(Iterator it2 = list.iterator();it2.hasNext();){
System.out.println(it2.next());
} //方法3 常用的,而且不用迭代器
for(String tmp:list){
System.out.println(tmp);
} //方法4 和C很像的
for(int i = 0;i < list.size(); i ++){
System.out.println(list.get(i));
} }
}