JAVA--List接口

List代表一个有序集合,集合中的每一个元素都有索引,允许重复元素,默认按添加元素的顺序添加索引,第一个元素的索引为0

List和ListIterator接口

List为Collection的子接口可以使用其所有方法
常用方法

方法 描述
void add(int index, Object element) 将元素elment插入在集合list的index处
boolean addAll(int index, Collection c) 将集合c中的元素插入到集合List的index处
Object get(int index) 返回List集合index索引处的元素
Int indexOf(Object o) 返回集合中元素o的index索引
int lastIndexOf(Object o) 返回集合中最后一个元素的索引
Object remove(int index) 删除集合index索引处的元素
Object setObject(int index, Object o) 将集合中index索引处的元素替换成o
List subList(int fromIndex,int toIndex) 返回集合中从索引fromIndex到toIndex索引处的元素集合

代码示例

import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class arrayListTest {
  public static void main(String[] grgs){
      //创建一个list集合,元素类型就是
      List books = new ArrayList();//类似OC中的可变数组
      //向list中添加元素
      books.add(new String("海的女儿"));
      books.add(new String("卖火柴的小女孩"));
      books.add(new String("老人与海"));
      //循环输出list中的元素
      for(int i = 0 ;i < books.size(); i++){//<=会发生越界  注意数组越界问题
          System.out.println(books.get(i));
      }
      //修改list中索引为1的元素
      books.set(1, "新版海的女儿");
      //删除books中索引为2的元素
      books.remove(1);
      //输出books
      System.out.println(books.get(1));
      //输出list中的部分元素
      System.out.println(books.subList(0, 2));
      //将list作为元素添加到Collection
      HashMap map = new HashMap();
      map.put("books", books);
      map.put("newbooks", books);
      System.out.println(map);
       System.out.println(map.get("books"));
  }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Interface List 在Java.util包中,继承自Collection,Iterable。 实现Lis...
    大煤球CUMT阅读 893评论 0 0
  • Collection ├List │├LinkedList │├ArrayList │└Vector │└Stac...
    AndyZX阅读 893评论 0 1
  • 3.3 集合 一方面, 面向对象语言对事物的体现都是以对象的形式,为了方便对多个对象的操作,就要对对象进行存储。另...
    闫子扬阅读 752评论 0 1
  • java源码分析之List接口以及ArrayList、LinkedList、Stack、Vector等实现类 Li...
    妖云小离阅读 677评论 0 0
  • 石家庄二组罗小霞 2017年6月19日14点43分,和往常一样,G2610次列车从太原开出后,列车员罗小...
    小霞美眉阅读 283评论 0 0