Java-Generic Learning

Source: Internet
Author: User
Tags class definition comparable naming convention uppercase letter


package com.fish.genrictiry;import java.util.arraylist;/*  generics are a new feature used by jdk1.5.      Benefits of generics:  1.  The runtime exceptions to the compile time.   2.  avoids unnecessary coercion of type conversions  . Common applications for      generics in collections:     arraylist<string>  list =  new ArrayList<String> ();  true      recommended for use.     ArrayList<Object>  list = new ArrayList<String> () ;   false  arraylist<string>  list = new arraylist<object > ();   false    //the following two kinds of writing are mainly to take into account the dual use of the new and old system problems.    *     ArrayList<String>  list = new  ArrayList ();           true          arraylist    list = new arraylist&Lt String> ();   true     Note that there is no concept of polymorphism in:  generics, the data   type must be   consistent between the left and right sides. Or just write one side of the generic type. It is recommended to write generics on both sides of: .    requirements:  All the elements in a collection into uppercase.   */ public class demo1 {    public static void  main (String[] args)  {        ArrayList<String>   list = new ArrayList<String> ();  //<string>  Indicates that the container can only store data of type   string.         list.add ("AA");         list.add ("BB");         list.add ("CC");                          for (Int i = 0 ; i < list.size ()  ; i++) {            &nBsp String str =  list.get (i);           &NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Uppercase:" + str.touppercase ());         }                myutil.print ( List);        arraylist<string> list2 =  Myutil.getlist ();         }}


Package Com.fish.genrictiry;import java.util.arraylist;//is written by an old programmer. It was written when jdk1.4.    public class Myutil {public static ArrayList getList () {return new ArrayList (); public static void print (ArrayList list) {for (int i = 0; i < list.size (); i++) {SYSTEM.OUT.PR        Intln (List.get (i)); }     }}


package com.fish.genrictiry;/*  Requirements:  defines a method that can receive parameters of any type, and the return value type must be   consistent with the type of the argument.    Custom generics:   a custom generic is a placeholder for a data type or a variable of a data type.    method Custom Generic:   modifier   < declare custom generic > return value type      function name (using custom generics   ...) {  }  cannot use the base data type in generics, and if you need to use a basic data type, use the wrapper type that corresponds to the base data type.  byte----> byte short---> short  int----> integer long---- > Long   double ----> Double  float -----> float   boolean-----Boolean  char-------" Character     Methods Generic Considerations:  1.  to customize generics on a method, the specific data type of this custom generic is when the   method is called to determine the specific data type when the argument is passed in.  2.  custom generics as long as you have a naming convention that conforms to the identifier  ,  but custom generics we're generally used to using an uppercase letter.   T Type  E Element  */public class Demo2 {     public static void main (String[] args) &NBSP;{&NBSP;&NBSP;&NBSP;&NBsp;        string str = getdata ("abc");             integer i = getdata (123);         }    public static <abc>abc  getdata (Abc o) {        return o;     }}
package com.fish.genrictiry;import java.util.arraylist;/*  Requirements:  Write an array of   tool classes    Generic class:  generic class definition Format:class  class name < declaring custom generics >{}  generic class things to be aware of: 1.  The specific data type of a custom generic on a class is determined when the object is created when the class is used.  2.  if a class has declared a custom generic on a class, and if you use the class to create object   without specifying a specific data type for   generics, then the object type  3 is the default. A custom generic on a class cannot act on a static method, and if a static method needs to use a custom generic, it needs to be declared on the method itself.     */class myarrays<t>{    //element Flip      Public void reverse (T[] arr) {        for (int  startindex = 0, endindex = arr.length-1 ; startindex<endindex ;  startindex++,endindex--) {            t  temp  = arr[startindex];             arr[startindex] = arr[endindex];            arr[endindex] = temp;        }     }    //    public string tostring (T[]  arr) {        stringbuilder sb = new  StringBuilder ();         for (int i = 0 ; i  < arr.length ; i++) {             if (i==0) {                 sb.append ("[" +arr[i]+ ",");             }else  if (i==arr.length-1) {                 sb.append (arr[i]+ "]");             } Else{     &nbSp;          sb.append (arr[i]+ ",");             }        }         return sb.tostring ();    }     public static <t>void print (t[] t) {    }     }public class demo3 {    public static void main ( String[] args)  {        integer[] arr = { 10,12,14,19};        myarrays<integer> tool = new  MyArrays<Integer> ();         tool.reverse (arr);         system.out.println ("Elements of the array:" +tool.tostring (arr));         &nbSp;       myarrays<string> tool2 = new myarrays <String> ();         string[] arr2 = {"AAA", "BBB", " CCC "};        tool2.reverse (ARR2);                 arraylist<string> list = new  ArrayList<String> ();     }}


Package com.fish.genrictiry;/* generic interface generic interface Definition Format: interface Interface name < declaration custom generic >{} generic interface Note: 1. The specific data type of a custom generic on an interface is specified when implementing an interface. 2. Generics that are customized on the interface if you do not specify a specific data type when implementing an interface, the default is the object type. Requirements: At the moment I implement an interface, I am not clear about the type of data I am currently working on, and I am waiting to create an interface implementation class object before I can specify the specific data type of the generic type. If you want to extend the specific data type of the interface custom generic, the format is as follows: Format: public class Demo4<t> implements Dao<t>{}*/interface dao<t>{public void Add (t t); }public class Demo4<t> implements dao<t> {public static void main (string[] args) {demo4<string& Gt    D = new demo4<string> (); } public void Add (T t) {}}


package com.fish.genrictiry;import java.util.arraylist;import java.util.collection;import  java.util.hashset;/*  the upper and lower bounds of a generic:  requirements 1:  Define a function that can receive a collection object of any type,  Collection objects that are required to be received can store only integer or integer parent class type data. Requirements 2:  defines a function that receives a collection object of any type,  requires that the collection object to be received can store only the subclass type data of number or number. Wildcard characters in generics:  ?  ? super Integer :  can store only an integer or an integer parent class element.    generic   Low limit   ? extends Number :  only subclass data with number or number type can be stored.   Generic Limit  */public class demo5 {    public static void  main (String[] args)  {        ArrayList<Integer>  list1 = new ArrayList<Integer> ();         Arraylist<number> list2 = new arraylist<number> ();         hashset<string> set = new hashset<sTring> ();         //getdata (set);    }         //Generic Cap     public static void  GetData (collection<? extends number> c) {    }         //the lower bound of the generic     public static void print (Collection<?  super integer> c) {        }}




Summarize:


A system of single-instance collections:

---------| Collection the root interface of a singleton collection

------------| List if it is a collection class that implements the list interface, features: Orderly, repeat.

---------------| Arrarylist Bottom is the use of an object array implementation, features: Fast query speed, and delete slow.

---------------| LinkedList Bottom is the use of linked list data structure to achieve, features: Slow query speed, and delete quickly.

---------------| Vector vectors are implemented in the same ArrayList, but are thread-safe and operate inefficiently. jdk1.0, when it came up.

------------| Set if it is a set interface implementation of the collection class, with the characteristics: unordered, non-repeatable.

----------------| The HashSet bottom is supported by a hash table, which features: fast access speed.

HashSet the principle of adding elements:

To add elements to HashSet, first HashSet calls the element's Hashcode method to get the hash code value of the element and then passes through a series of operations

You can figure out where the element is stored in the hash table/

Scenario 1: If the position of the element is not currently stored in any element, then the element can be stored directly

Scenario 2: If the position of the element is currently present with other elements, then the Equals method of the element is also called to compare with the element at that location.

If the Equals method returns False, then the element is allowed to be stored, and if the Euqlas method returns True, then the element is treated as a repeating element and is not allowed to be stored.

------------------| The bottom of the TreeSet is implemented using a red-black tree (binary tree) data structure, characterized by the ordering of the elements to be stored.


TreeSet things to be aware of:

1. When adding elements to TreeSet, if the elements themselves have natural order characteristics, they are sorted according to the nature of the elements ' natural order.

2. When adding elements to TreeSet, if the element itself does not have a natural order, then the class to which the element belongs must implement the comparable interface, defining the element's comparison rule

On the CompareTo method.

3. When adding elements to TreeSet, if the element itself does not have a natural order, and the class to which the element belongs does not implement the comparable interface, you must create

TreeSet the object when it is passed into the comparer.

4. If the method of comparison (CompareTo or Compare) returns 0, then the element is treated as a repeating element and is not allowed to be added.

Definition format for comparators: Customizing a class to implement the comparator interface.

Class name implements Comparator{

}


Generics: Generics are a new feature that appears in jdk1.5.


Benefits of Generics:

1. Advance the run-time problem to compile time.

2. Avoid the unnecessary coercion type conversion.

Custom generics: A custom generic is a placeholder for a data type or a variable that is understood as a data type.

Generic methods:

Modifier < DECLARE custom generic > Return value type function name (custom generic variable name ...)

Things to keep in mind about generic methods:

1. The specific data type of a custom generic in a generic method is determined when the argument is passed in when the function is called.

2. The identifier used by the custom generic is as long as it conforms to the naming convention of the identifier. But we are generally accustomed to using an uppercase letter to denote.


Generic class:


Definition Format for generic classes

Class name < declaration custom generic >{

}


Things to note about generic classes:

1. A custom generic on a generic class specifies a specific data type when the object is created using that class.

2. If a class has been customized with generics, the object type is the default if no specific data type of the generic is specified when the class is created.

3. A static function cannot use a custom generic on a class, and if a static function needs to be used, you must customize the generic on the function.


Generic interface:


Definition format for generic interfaces:

Interface interface name < declaration custom generic >{

}

Generic interface considerations:

1. A custom generic on a generic interface specifies a specific data type when the interface is implemented.

2. If you implement an interface without specifying the specific data type of the custom generic on the interface, the default is the object data type.

3. If you need to specify a custom generic on an interface when creating an interface implementation class object, you need the following format: class<t> class name implements interface <T>


Generic upper and lower bounds:

? Super integer allows the lower bound of the integer data type or the integer parent class type generic

? Extedns number allows the upper bound of the data type generic for the number data type or the number subclass.




This article from "Small Fish Blog" blog, declined reprint!

Java-Generic Learning

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.