List集合

来源:互联网 发布:java 取整数部分 编辑:程序博客网 时间:2024/06/16 13:15

List

List作为Collection接口的子接口,下面是常用的方法

void add(int index,Object element):
boolean addAll(int index,Collection c):
Object get(int index):
int indexOf(Object o):
int lastIndexOf(Object o):
Object remove(int index):
Object set(int index,Object element):
List subList(int fromindex,int toindex):
void replaceAll(UnaryOperator operator):
void sort(Comparator c):

public class ListTest{    public static void main(String[] args)    {        List books = new ArrayList();        // 向books集合中添加三个元素        books.add(new String("轻量级Java EE企业应用实战"));        books.add(new String("疯狂Java讲义"));        books.add(new String("疯狂Android讲义"));        System.out.println(books);        // 将新字符串对象插入在第二个位置        books.add(1 , new String("疯狂Ajax讲义"));        for (int i = 0 ; i < books.size() ; i++ )        {            System.out.println(books.get(i));        }        // 删除第三个元素        books.remove(2);        System.out.println(books);        // 判断指定元素在List集合中位置:输出1,表明位于第二位        System.out.println(books.indexOf(new String("疯狂Ajax讲义"))); //①        //将第二个元素替换成新的字符串对象        books.set(1, new String("疯狂Java讲义"));        System.out.println(books);        //将books集合的第二个元素(包括)        //到第三个元素(不包括)截取成子集合        System.out.println(books.subList(1 , 2));    }}
public class ListTest3{    public static void main(String[] args)    {        List books = new ArrayList();        // 向books集合中添加4个元素        books.add(new String("轻量级Java EE企业应用实战"));        books.add(new String("疯狂Java讲义"));        books.add(new String("疯狂Android讲义"));        books.add(new String("疯狂iOS讲义"));        // 使用目标类型为Comparator的Lambda表达式对List集合排序        books.sort((o1, o2)->((String)o1).length() - ((String)o2).length());        System.out.println(books);        // 使用目标类型为UnaryOperatorLambda表达式来替换集合中所有元素        // 该Lambda表达式控制使用每个字符串的长度作为新的集合元素        books.replaceAll(ele->((String)ele).length());        System.out.println(books); // 输出[7, 8, 11, 16]    }}
原创粉丝点击