【java】List接口

来源:互联网 发布:武汉java工作好找吗 编辑:程序博客网 时间:2024/04/24 23:33

参考文章:

Java list的用法排序及遍历

1.list可以添加任何对象,包括自定义的类对象

//定义了一个Person类class Person{.....}//添加到中去Person p1=new Person();Person p2=new Person();List list=new ArrayList();list.add(p1);list.add(p2);for(int i=0;i<2;i++)Person p=(Person) list.get(i);//注意,这里一定要强制类型转换,因为List中取出的对象都是Object类型的,主要原因在与list本身没有使用泛型}

2.list只是一个接口,不要进行实例化操作。

List接口实现的类:ArrayList(动态数组) Vector(动态数组) LinkedList(链表)Stack(栈)

package study;import java.util.ArrayList;/** * https://www.tutorialspoint.com/java/java_arraylist_class.htm * 继承AbstactList 实现List接口 * 动态数组 * 常规的增删改查都有 * void ensureCapacity(int minCapacity) * Object[] toArray()---Returns an array containing all of the elements in this list in the correct order. Throws NullPointerException if the specified array is null. * void trimToSize()---Trims the capacity of this ArrayList instance to be the list's current size. */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);    }}

package study;import java.util.Iterator;import java.util.LinkedList;/** * https://www.tutorialspoint.com/java/java_linkedlist_class.htm * extends AbstractSequentialList and implements the List interface * ListIterator listIterator(int index)---Returns a list-iterator of the elements in this list (in proper sequence),starting at the specified position in the list. * Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >= size()). */public class LinkedListDemo {    public static void main(String args[]) {        // create a linked list        LinkedList ll = new LinkedList();        // add elements to the linked list        ll.add("F");        ll.add("B");        ll.add("D");        ll.add("E");        ll.add("C");        ll.addLast("Z");        ll.addFirst("A");        ll.add(1, "A2");        //System.out.println("Original contents of ll: " + ll);   //其实这样就已经可以输出所有的内容        //使用Iterator迭代器遍历出集合的元素并打印        for(Iterator i = ll.iterator(); i.hasNext(); ){            String str = (String)i.next();            System.out.println(str);        }        // remove elements from the linked list        ll.remove("F");        ll.remove(2);        System.out.println("Contents of ll after deletion: " + ll);        // remove first and last elements        ll.removeFirst();        ll.removeLast();        System.out.println("ll after deleting first and last: " + ll);        // get and set a value        Object val = ll.get(2);        ll.set(2, (String) val + " Changed");        System.out.println("ll after change: " + ll);    }}

package study;import java.util.EmptyStackException;import java.util.Iterator;import java.util.Stack;/** * peek pop push search empty */public class StackDemo {    static void showpush(Stack st, int a) {        st.push(new Integer(a));        System.out.println("push(" + a + ")");        System.out.println("stack: " + st);    }    static void showpop(Stack st) {        System.out.print("pop -> ");        Integer a = (Integer) st.pop();        System.out.println(a);        System.out.println("stack: " + st);    }    public static void main(String args[]) {        Stack st = new Stack();//只有一个不带参数的默认构造函数        System.out.println("stack: " + st);        showpush(st, 42);        showpush(st, 66);        showpush(st, 99);        showpop(st);        showpop(st);        showpop(st);        try {            showpop(st);        }catch (EmptyStackException e) {            System.out.println("empty stack");        }        Stack al = new Stack();        al.push("a");        al.push("b");        al.push("c");        al.push("d");        al.push("f");        //使用Iterator迭代器遍历出集合的元素并打印        for(Iterator i = al.iterator(); i.hasNext(); ){            String str = (String) i.next();            System.out.println(str);        }    }}

package study;import java.util.Enumeration;import java.util.Vector;/** Enumeration elements()---Returns an enumeration of the components of this vector. */public class VectorDemo {    public static void main(String args[]) {        // initial size is 3, increment is 2        Vector v = new Vector(3, 2);        System.out.println("Initial size: " + v.size());        System.out.println("Initial capacity: " + v.capacity());        v.addElement(new Integer(1));        v.addElement(new Integer(2));        v.addElement(new Integer(3));        v.addElement(new Integer(4));        System.out.println("size after four additions:  " + v.size());        System.out.println("Capacity after four additions: " + v.capacity());        v.addElement(new Double(5.45));        System.out.println("Current capacity: " + v.capacity());        v.addElement(new Double(6.08));        v.addElement(new Integer(7));        System.out.println("Current capacity: " + v.capacity());        v.addElement(new Float(9.4));        v.addElement(new Integer(10));        System.out.println("Current capacity: " + v.capacity());        v.addElement(new Integer(11));        v.addElement(new Integer(12));        System.out.println("First element: " + (Integer)v.firstElement());        System.out.println("Last element: " + (Integer)v.lastElement());        if(v.contains(new Integer(3)))            System.out.println("Vector contains 3.");        // enumerate the elements in the vector.        Enumeration vEnum = v.elements();        System.out.println("\n Elements in vector:");        while(vEnum.hasMoreElements())            System.out.print(vEnum.nextElement() + " ");        System.out.println();    }}

3.排序

数字排序

public static void main(String[] args) {    // 创建list    List<Integer> list = new ArrayList<Integer>();    // 插入元素    list.add(2);    list.add(0);    list.add(3);    list.add(4);    list.add(1);    Collections.sort(list);    for (int i : list) {        System.out.println(i);    }}

中文排序--需要加中文比较规则

public static void main(String[] args) {    ArrayList<String> list = new ArrayList<String>();    list.add("一鸣惊人-Y");    list.add("人山人海-R");    list.add("海阔天空-H");    list.add("空前绝后-K");    list.add("后来居上-H");    Comparator<Object> cmp = Collator.getInstance(java.util.Locale.CHINA);    Collections.sort(list, cmp);    for (String str : list) {        System.out.println(str);    }}


实体类排序---自定义比较规则

package net.xsoftlab.baike;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;public class TextList {    public static void main(String[] args) {        List<User> userlist = new ArrayList<User>();        userlist.add(new User("Y - 易小星 ", 33));        userlist.add(new User("W - 王大锤", 33));        Comparator<User> cmp = new ComparatorUser();        Collections.sort(userlist, cmp);        for (User user : userlist) {            System.out.println(user.getName());        }    }}class ComparatorUser implements Comparator<User> {    @Override    public int compare(User u1, User u2) {        // 先按年龄排序        int flag = u1.getAge().compareTo(u2.getAge());        // 年龄相等比较姓名        if (flag == 0) {            return u1.getName().compareTo(u2.getName());        } else {            return flag;        }    }}class User {    private String name;    private Integer age;    public User() {        super();    }    public User(String name, Integer age) {        super();        this.name = name;        this.age = age;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Integer getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }}


之前自己写过代码:

package study;import java.util.*;public class Myexception {    public static void main(String[] args) {        List<Integer> arrayList = new ArrayList<Integer>();        arrayList.add(1); // 1 is autoboxed to new Integer(1)        arrayList.add(2);        arrayList.add(3);        arrayList.add(1);        arrayList.add(4);        arrayList.add(0, 10);        arrayList.add(3, 30);        //相当于前面的功能,这是java提供的静态的aslist方法        //需要注意的就是我asList面对基本数据类型的时候,将整个数组作为一个“数字”的情况  http://blog.csdn.net/lzm18064126848/article/details/53823610   /* List<String> list1 = Arrays.asList("red","green","blue");    List<Integer> list2 = Arrays.asList(10,20,30,40,50);*/        System.out.println("A list of integers in the array list:");        System.out.println(arrayList);//三种输出方式   直接List名称  for循环   Iterator迭代器        //因为后面又添加了String类对象,这和之前Integer不一样,因此需要Object        //new LinkedList<Object>(arrayList);直接就在函数参数里面添加上一个arraylist,这样就相当于直接包含了上一个        //数组线性表        LinkedList<Object> linkedList = new LinkedList<Object>(arrayList);        linkedList.add(1, "red");        linkedList.removeLast();        linkedList.addFirst("green");        System.out.println("Display the linked list forward:");        //System.out.println(linkedList);        //hasNext()是从前往后遍历        ListIterator<Object> listIterator = linkedList.listIterator();        while (listIterator.hasNext()) {            System.out.print(listIterator.next() + " ");        }        System.out.println();        //hasPrevious()是从后往前遍历        System.out.println("Display the linked list backward:");        listIterator = linkedList.listIterator(linkedList.size());        while (listIterator.hasPrevious()) {            System.out.print(listIterator.previous() + " ");        }    }}


0 0
原创粉丝点击