Collection --List

1. Why use a collection

For example: data storage
data may be stored in an array, the array has significant drawbacks before, upon determining the length, would not be able to modify, delete or add elements if so, requires a large amount of movement of the element position.
Array: only put one data type, it can be basic data types can also be a reference data types

The head office can be used to solve the problem set:

Set of advantages: increased efficiency of high-removing elements
characteristic of the collection: A collection can have multiple data types (general use generics, only store one data type), but he can only store reference data types

2. The structure of the set of FIG.

Here Insert Picture Description

3. The set of application scenarios

When an individual needs to be integrated into the same structure when together, to take into account a set.

4.ArrayList

  • ArrayList of use
public class Test {
    public static void main(String[] args) {
        Collection collection=new ArrayList();//接口new实现类
        System.out.println("集合是否为空:"+collection.isEmpty());
        //(1)添加元素
        collection.add("hello");
        collection.add(new Date());
        collection.add(123);
        collection.add("hello");
        collection.add(new Person("lisli",29, Gender.));
        System.out.println("集合是否为空:"+collection.isEmpty());
        System.out.println("集合中元素的个数:"+collection.size());
        System.out.println(collection);
        System.out.println(collection.remove("hello")); //将第一个hello删除
        //collection.clear();
        System.out.println(collection);
        System.out.println(collection.contains(123));
        Collection collection1=new ArrayList();
        collection1.add("world1");
        collection1.add("world2");
        collection1.add("world3");
        collection.addAll(collection1);
        System.out.println(collection);
        //遍历集合
        System.out.println("---------------------------------------");
        for(Object obj:collection){
            System.out.println(obj);//默认调用toString()方法
        }
        System.out.println("------------------自己使用迭代器遍历元素 hasNext() ,next()---------------------------");
        Iterator  ite= collection.iterator();
        while(ite.hasNext()){  //true就说明集合中有数据,为false,说明集合中没有数据,可以退出循环
           Object obj= ite.next();
            System.out.println(obj);
        }
    }
}

  • The underlying structure ArrayList
    ArrayList: Object Type is an array of packages
    to create ArrayList object (1) when the constructor with no arguments to call ArrayList
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; //初始长度为0,在堆里开空间了
         transient Object[] elementData; //声明一个Object类型的数组,并没有new对象
        public ArrayList() {
            this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; //指向 是长度为0的那个数组
     }

(2) when the first call add () method to add elements to the array of type Object initial capacity of 10

private int size; //集合中元素的个数 ,默认值为0
      private static final int DEFAULT_CAPACITY = 10;
public boolean add(E e) {
        ensureCapacityInternal(size + 1);  //调用本类中的方法 
        elementData[size++] = e;
        return true;
    }
        
        private void ensureCapacityInternal(int minCapacity) {//minCapacity 的值为1
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }
        
        private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {//第一次调用add方法时执行
            return Math.max(DEFAULT_CAPACITY, minCapacity); //return Math.max(10,1);
        }
        return minCapacity;
    }
  private void ensureExplicitCapacity(int minCapacity) { //计算出来的最小容量为10
        modCount++;
        // overflow-conscious code
        if (minCapacity - elementData.length > 0) //10-0>0?true 说明数组的长度已完全不够用
            grow(minCapacity);
    }
        
        private void grow(int minCapacity) {  //10
        // overflow-conscious code
        int oldCapacity = elementData.length;  //oldCapacity= 0
        int newCapacity = oldCapacity + (oldCapacity >> 1);  //0+0 结果为 newCapacity=0
        if (newCapacity - minCapacity < 0)   //0-10<0 true
            newCapacity = minCapacity;          //newCapacity=10;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);   //数组拷贝
    }

(3) when the eleventh call add () method, the expansion of the array 15
int + newCapacity = oldCapacity (oldCapacity >>. 1);
deletions of the investigation is to change the ArrayList deletions array type Object change search
advantages of ArrayList : save storage space, according to the index query high efficiency
disadvantages of ArrayList: delete, add the need to move large number of elements, low efficiency, according to the contents one by one to find the main comparative judgments, inefficient

  • LinkedList use
public class Test2 {
    public static void main(String[] args) {
        Collection collection=new LinkedList();//接口new实现类
        System.out.println("集合是否为空:"+collection.isEmpty());
        //(1)添加元素
        collection.add("hello");
        collection.add(new Date());
        collection.add(123);
        collection.add("hello");
        collection.add(new Person("lisli",29, Gender.));
        System.out.println("集合是否为空:"+collection.isEmpty());
        System.out.println("集合中元素的个数:"+collection.size());
        System.out.println(collection);
        System.out.println(collection.remove("hello")); //将第一个hello删除
        //collection.clear();
        System.out.println(collection);
        System.out.println(collection.contains(123));
        Collection collection1=new LinkedList();
        collection1.add("world1");
        collection1.add("world2");
        collection1.add("world3");
        collection.addAll(collection1);
        System.out.println(collection);
        //遍历集合
        System.out.println("---------------------------------------");
        for(Object obj:collection){
            System.out.println(obj);//默认调用toString()方法
        }
        System.out.println("------------------自己使用迭代器遍历元素 hasNext() ,next()---------------------------");
        Iterator  ite= collection.iterator();
        while(ite.hasNext()){  //true就说明集合中有数据,为false,说明集合中没有数据,可以退出循环
           Object obj= ite.next();
            System.out.println(obj);
        }
    }
}
  • LinkedList
    underlying data structure is a linked list LinkedList, using a doubly linked list
transient Node<E> first;  //默认值均为null
 transient Node<E> last;
 
  public boolean add(E e) {
        linkLast(e);
        return true;
    }
        
        void linkLast(E e) {
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null); //当调用add方法时,new Node创建节点对象
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        modCount++;
    }
        //LinkedList中的私有静态内部类
       private static class Node<E> {
        E item;  //当前要存储的元素
        Node<E> next;  //后继节点
        Node<E> prev;  //前驱节点
        Node(Node<E> prev, E element, Node<E> next) {  //创建一个节点对象
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }

Advantages: delete, add an element to be moved, high efficiency (but you need to navigate to the elements)
Cons: Each element node, specifically an increase of address space to store the next element, take up more space, each node addresses continuous, irregular, resulting in low efficiency in accordance with the index query

  • Use iterator object through the elements, add elements
public class Test2 {
    public static void main(String[] args) {
        List list=new ArrayList();
        list.add("java");
        list.add("hello");
        list.add("world");
        list.add("sql");
        //想在遍历集合时添加元素
      // Iterator ite= list.iterator();
        ListIterator ite=list.listIterator();
       while(ite.hasNext()){
           Object obj=ite.next();
           if(obj.equals("hello")){
               ite.add("html");
           }
       }
        System.out.println(list);
    }
}

5. Generics

Set of types of data elements stored in the collection of objects to be limiting when creating a
generic symbol used <data type>
before javac: generic functions of time

public class Test {
    public static void main(String[] args) {
    	//创建集合对象时,规则了集合中存储的元素的数据类型只能是String类型
      List<String> list=new ArrayList<String>();
      
      list.add("hello");
      list.add("java");
      list.add("world");
    //  list.add(123);
      
    }
}

Generic classification

(1) generic interface

public interface Collection<E>{  //E代表一种数据类型,这个类型什么时候才能知道
}
 //在创建接口的实现类对象时,才能知道,在如下代码中,E所代表的数据类型是Integer
 Collection<Integer> coll=new ArrayList<Integer>();

(2) generic class

public class ArrayList<E>{  //E的数据类型什么时候知道,创建ArrayList对象时知道

}
  ArrayList<String> al=new ArrayList<String>();

(3) a generic method

public boolean add(E e) {}
  //E也代表一种数据类型 ,这个E的数据类型与ArrayList<E> 完全相同的,所以E的类型是在创建ArrayList的对象时确定


Variable parameter generic method:
(1) is a variable parameter JDK1.5
(2) is a generic JDK1.5

public class Test {
    public static void main(String[] args) {
        Client<String> client=new Client<String>();//T的类型是String
        client.show("hello");
        //泛型方法,数据类型是在调用该方法时明确的,解决了同一个类中参数个数相同,类型不同的方法重载问题
        client.fun("hello");
        client.fun(123);
        client.fun(new Date());
         //可变参数的泛型方法,解决了数据类型不同,个数不同的方法重载问题
        client.method("hello");
        client.method("world1","world2","world3");
        client.method(123);
        client.method(8.7,9.8,7.6,9.9);
       //可变参数实际上就是一个数组
        Client<Integer> client2=new Client<Integer>();//T的类型时Integer
        client2.show(123);
    }
}
Published 37 original articles · won praise 8 · views 2232

Guess you like

Origin blog.csdn.net/penerx/article/details/104356607