Java Advanced technology: Generic

Generics

concept:

  • public class LinkedList
  • extends AbstractSequentialList
  • implements List, Deque, Cloneable, java.io.Serializable{}
  • public interface Deque extends Queue {}
  • public interface Queue extends Collection {}
  • public interface Collection extends Iterable {}

We appear in the above code <?> Is what is it, it is called generics, and a collection of objects used to be used together, so our Before starting a collection, you must first understand what is generic. And the generic concept is very important, it is an enhancement program, which is currently the mainstream development approach.

Generics are (Generics) is a new feature of JDK1.5, in fact, a "syntactic sugar" means essentially a small-compiler in order to provide better readability and provided tips, a virtual machine level It is the concept of so-called "generic" does not exist.

effect:

  • The syntax defined by generic constraint type element in the collection, security checks, the error is displayed at compile time
  • Code is more versatile, there are cases behind
  • Generics can improve the readability of the program code, but it's just a syntactic sugar (such a thing was compiled deleted, do not appear in the final source code) for the JVM run-time performance is of no effect.

Generic declaration:
Generic interface can be, method, use return value:

  • java.util.List generic interface / class:
    public interface Collection {}
  • Statement generic method:
    public void Print (E E)} {
  • In the former method returns a value statement indicating the occurrence of back E is a generic, rather than ordinary java variables.

Common name:

  • E - Element (used in the collection, since the collection is stored in the element)
  • T - Type (Java class)
  • K - Key (键)
  • V - Value (Value)
  • N - Number (numeric types)
  • ? - indicates the type of uncertainty java
public class Test1 {
    public static void main(String[] args) {
       int[] a = new int[3];
       a[0]=1;
       a[1]=2;   
       //int类型的数组,规定了数组里的数据类型,类型不对就报错。
//     a[2]="hello";       
       //1,泛型的标志<>
       //2,泛型的好处:规定了数据的类型,不能想放什么数据就放什么类型,要遵守泛型规定的类型
       //3,泛型的数据类型只能是引用类型,不能是基本类型
       List<Integer> list = new ArrayList<Integer>();
       list.add(1);
       list.add(2);
       
//4,如果类型不对,把运行时期才会 报的错ClassCastException直接在编译时期就报出来

//     list.add("a");
//     list.add('b');       
       Iterator it = list.iterator();
       while(it.hasNext()) {
           Integer s = (Integer) it.next();
           System.out.println(s);
       }      
    }
  • Code is more versatile
  • By overloading the conventional manner to achieve polymorphism, a method of the same name, the different types of parameters.
public class TestOldStyle {
    public static void print(Integer[] dArray) {
       for( Integer d : dArray) {
           System.out.println(d);
       }
    } 
    
    public static void print( String[] sArray) {
       for( String s : sArray) {
           System.out.println(s);
       }
    }   
    
    public static void main(String[] args) {
       Integer[] scores = new Integer[]{100,98,80};
       String[] names = new String[]{"语文","数学","英语"};      
       TestOldStyle.print(scores);
       TestOldStyle.print(names);
    }
}

Generic way:

public class TestGenarics {
    public static <E> void print(E[] arr) {
       for(E e : arr) {
           System.out.println(e);
       }
    } 
    
    public static void main(String[] args) {
       Integer[] scores = new Integer[]{ 100,98,80 };
       String[] names = new String[]{ "语文","数学","英语" };
       Double[] moneys = new Double[] { 10.1,20.2,30.3 };      
       TestGenarics.print(scores);
       TestGenarics.print(names);
       TestGenarics.print(moneys);
    }
}

Collection Interface

Overview:

  • English name Collection, is used to store the object data structure. Wherein the variable length, and the collection can be stored in different types of objects. And provides a method of operating a set of objects in batches.
  • Array disadvantages: complicated invariable length is fixed, a single access mode, insert, or delete operation.

Inheritance structure collection
Here Insert Picture Description

>Collection接口

>-- List接口  : 数据有序,可以重复。

   -- ArrayList子类

   -- LinkedList子类

>-- Set接口  : 数据无序,不可以存重复值

   -- HashSet子类

>-- Map接口  : 键值对存数据

   -- HashMap

>-- Collections工具类
Common methods:
  • boolean add (E e): additive element.
  • boolean addAll (Collection c): adding a set of small to large collection.
  • boolean contains (Object o): if this collection contains the specified element, it returns true.
  • boolean isEmpty (): If there is no element of this collection, it returns true.
  • Iterator iterator (): returns an iterator in the elements of this collection.
  • boolean remove (Object o): removed from this collection a single instance of the specified element.
  • int size (): returns the number of elements in this collection.
  • Objec [] toArray (): Returns an array of objects

List interface:

An ordered collection (also known as a sequence). This user interface can be accurately controlled to the insertion position of each list element. Users can access elements based integer index (position in the list), and search for elements in the list.

Features:
1, data ordered
2, allowing repeat storage element
3, the element has an index

Common methods:

ListIterator listIterator ()

  •      返回此列表元素的列表迭代器(按适当顺序)。
    

ListIterator listIterator (int index)

  •      返回列表中元素的列表迭代器(按适当顺序),从列表的指定位置开始。
    

void add(int index, E element)

  •      在列表的指定位置插入指定元素(可选操作)。
    

boolean addAll(int index, Collection<? extends E> c)

  •      将指定 collection 中的所有元素都插入到列表中的指定位置(可选操作)。
    

List subList(int fromIndex, int toIndex)

  • 返回列表中指定的 fromIndex(包括 )和 toIndex(不包括)之间的部分视图。
    

E get(int index)

  •      返回列表中指定位置的元素。  
    

int indexOf(Object o)

  •      返回此列表中第一次出现的指定元素的索引;如果此列表不包含该元素,则返回 -1。
    

ArrayList

Overview:

  1. 存在于java.util包中。
    
  2. 内部用数组存放数据,封装了数组的操作,每个对象都有下标。
    
  3. 内部数组默认初始容量是10。如果不够会以1.5倍容量增长。
    
  4. 查询快,增删数据效率会降低。
    

Create an object:

  • new ArrayList (): Initial capacity 10

Common test methods:

public class Test3_AL {
       public static void main(String[] args) {
              ArrayList list = new ArrayList();
              list.add("aaa");//存入数据
              list.add("123");
              list.add("ccc");
              list.add("ddd");
              System.out.println(list);//list中内容
              System.out.println(list.size());//集合长度
              System.out.println(list.get(1));//根据下标获取元素                     
              System.out.println();
              System.out.println(list.remove(2));//移除下标对应的元素
              System.out.println(list);   
                                
               //下标遍历
	for (int i = 0; i < list.size(); i++) {
		System.out.print(list.get(i));
}
                     
       //Iterator迭代遍历,封装了下标
                     Iterator<String> it = list.iterator();
                     while (it.hasNext()) {//如果有数据
                            String s = it.next();//一个一个向后遍历
                            System.out.println(s);
                     }      
         }
}

LinkedList

Here Insert Picture Description
Common methods:

  • add() get()
  • size()
  • remove(i)
  • remove (data)
  • iterator()
  • addFirst() addLast()
  • getFirst() getLast()
  • removeFirst() removeLast()

Test iterates over, doubly linked list: the low standard traverse efficiency, high efficiency iterates over

public class tt {
       public static void main(String[] args) throws Exception {
              LinkedList ll = new LinkedList ();
              for (int i = 0; i < 100000; i++) {
                     ll.add(100);
              }
              f1(ll);
              f2(ll);
       } 
       private static void f2(LinkedList<Integer> ll) {
              long t = System.currentTimeMillis();
              Iterator it = ll.iterator();
              while(it.hasNext()) {
                     it.next();
              }
              t = System.currentTimeMillis()-t;
              System.out.println("=====iterator========="+t);//16
       } 
       private static void f1(LinkedList<Integer> ll) {
              long t = System.currentTimeMillis();
              for (int i = 0; i < ll.size(); i++) {
                     ll.get(i);
              }
              long t1 = System.currentTimeMillis();
              System.out.println("~~~~for~~~~~~~"+(t1-t));//9078
       }
}

Published 36 original articles · won praise 13 · views 1061

Guess you like

Origin blog.csdn.net/weixin_44598691/article/details/104847105