Java List集合方法及遍歷過程代碼解析


集合元素框架

public class ListDemo02 {
  public static void main(String[] args) {
    //創(chuàng)建集合對(duì)象
    List<String> list = new ArrayList<String>();

    //添加元素
    list.add("hello");
    list.add("world");
    list.add("java");

    //輸出集合對(duì)象
    System.out.println(list); //[hello, world, java]
  }
}

方法運(yùn)行實(shí)例

//void add(int index, E element) : 在此集合中的指定位置插入指定的元素
    list.add(1,"javaee"); //[hello, javaee, world, java]
    list.add(11,"j2ee");  //IndexOutOfBoundsException


//E remove(int index):刪除指定索引處的元素,返回被刪除的元素
    System.out.println(list.remove(1));
    /*
        world
        [hello, java]
     */


//E set(int index,E element):修改指定索引處的元素,返回被修改的元素
    System.out.println(list.set(1,"javaee"));
    /*
        world
        [hello, javaee, java]
     */


//E get(int index):返回指定索引處的元素
    System.out.println(list.get(1));
    /*
        world
        [hello, world, java]
     */
//用for循環(huán)改進(jìn)遍歷
    for (int i = 0; i<list.size();i++){
      String s = list.get(i);
      System.out.println(s);
    }
    /*
      hello
      world
      java
      [hello, world, java]
     */

List集合是帶索引的集合,要考慮越界問題。


最新2020整理收集的一些高頻面試題(都整理成文檔),有很多干貨,包含mysql,netty,spring,線程,spring cloud、jvm、源碼、算法等詳細(xì)講解,也有詳細(xì)的學(xué)習(xí)規(guī)劃圖,面試題整理等,需要獲取這些內(nèi)容的朋友請(qǐng)加Q君樣:11604713672

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容