java List集合

List包括List接口以及List接口的所有實現類。因爲Llist接口實現了collection接口,所以List接口擁有collection接口提供的所有常用方法,有因爲list是列表類型,所以List接口還提供了一些適合與自身的常用方法


Lsit接口提供給的是個與自身的常用方法均與索引右岸沒這是因爲list集合爲類別類型,以線性方式存儲對象,可以通過對象的索引操作對象

    Liat接口的常用實現類有ArrayList和LinledList,在使用List集合時,通常情況下生命爲List類型,實例化時根據實際情況的需要,實例化爲ArrayList(隊列)或LinledList(列表),例如

List<String>I = new ArrayList<String>();//了利用ArrayList類實例化List集合

List<String>I2 = new LinledList<String>();//了利用LinledList類實例化List集合



》》add(int index ,Object obj)方法和Set(int index ,Objectobj)方法

在使用List集合時需要注意區分add(int index ,Object obj)方法和Set(int index ,Objectobj)方法,前者是向指定索引位置(添加)對象,而後者是(替換)指定索引位置的對象,索引值從0開始



public class Example {
//Collection接口
public static void main(String[] args) {
String a = "A", b = "B", c = "C", d ="D" , e = "E";
Collection<String> list = new LinkedList<String>();
list.add(a);
list.add(e);
list.add(d);
//使用了轉換定義 也可以直接用 如:List.set(0,b);  List.add(1,c);
((LinkedList<String>) list).set(0,b);//將索引位置爲0 的對象a修改爲對象b
((LinkedList<String>) list).add(1,c);//將對象c添加到索引位置爲1的位置
Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}



>>indexOF(Objectobj)方法和IastIndexOf(Object obj)方法

在使用List集合時需要注意區分indexOF(Objectobj)方法和IastIndexOf(Object obj)方法,前置是獲得指定對象的最小的索引位置,而後者是獲得指定對象的最大的索引位置,前提條件是指定的對象在List集合中具有重複的對象,否則如果在List集合中有且僅有一個指定的對象,則通過這兩個方法獲得的索引位置是相同的 public static void main(String[] args) {
String a = "A", b = "B", c = "C", d ="D" ,repeat = "repeat";
Collection<String> list = new ArrayList<String>();
list.add(a); //索引位置爲0
list.add(repeat); //索引位置爲1
list.add(b); //索引位置爲2
list.add(repeat); //索引位置爲3
list.add(c); //索引位置爲4
list.add(repeat); //索引位置爲5
list.add(b); //索引位置爲6
//獲得索引最大和最小的位置 可以使用一下寫法  也可以使用另一種寫法 如System.out.println(list.indexOf(repeat));
System.out.println(((ArrayList<String>) list).indexOf(repeat)); //獲得指定對象的最小的索引位置
System.out.println(((ArrayList<String>) list).lastIndexOf(repeat)); //獲得指定對象的最大的索引位置
System.out.println(((ArrayList<String>) list).indexOf(b)); //獲得指定對象的最小的索引位置
System.out.println(((ArrayList<String>) list).lastIndexOf(b)); //獲得指定對象的最大的索引位置
}}



》》使用subList(int fromindex,int toindex)方法可以截取現有的List集合重的部分對象,生成新的List集合,需要注意的是萌新生成的集合中包含起始索引位置的對象,但是不包含終止做因位置的對象

截取索引1到3之間的集合






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章