ArrayList

2019-02-25  本文已影响0人  Harper324

ArrayList

ArrayList是一个可重复的有序列表,里面可以放相同的元素。

import java.util.*;
public class ArrayListDemo {

   public static void main(String args[]) {
      // create an array list
      ArrayList al = new ArrayList();
      System.out.println("Initial size of al: " + al.size());

      // add elements to the array list
      al.add("C");
      al.add("A");
      al.add("E");
      al.add("B");
      al.add("D");
      al.add("F");
      al.add(1, "A2");
      System.out.println("Size of al after additions: " + al.size());

      // display the array list
      System.out.println("Contents of al: " + al);

      // Remove elements from the array list
      al.remove("F");
      al.remove(2);
      System.out.println("Size of al after deletions: " + al.size());
      System.out.println("Contents of al: " + al);
   }
}

//输出结果
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
for (int i = 0; i < collection.size(); i++) {
    // some code
    // example: collection.get(i);
}

2、自动增强的for循环

for (Object obj : collection) {
    // some code
}

3、迭代器

Iterator<Object> it = collection.iterator();
while(it.hasNext()){
    // some code
    // example it.next()
}

例子

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

public class CrunchifyIterateThroughList {

    public static void main(String[] argv) {
        List<String> crunchifyList = new ArrayList<String>();

        crunchifyList.add("eBay");
        crunchifyList.add("Paypal");
        crunchifyList.add("Google");
        crunchifyList.add("Yahoo");

        System.out.println("==> For Loop Example.");
        for (int i = 0; i < crunchifyList.size(); i++) {
            System.out.println(crunchifyList.get(i));
        }

        System.out.println("\n==> Advance For Loop Example..");
        for (String temp : crunchifyList) {
            System.out.println(temp);
        }

        System.out.println("\n==> Iterator Example...");
        Iterator<String> crunchifyIterator = crunchifyList.iterator();
        while (crunchifyIterator.hasNext()) {
            System.out.println(crunchifyIterator.next());
        }
    }
}

//输出结果:
eBay
Paypal
Google
Yahoo
上一篇 下一篇

猜你喜欢

热点阅读