Java basics 18 -- generic -- tool class -- New Features of JDK1.5

Source: Internet
Author: User

18-1, generic-Overview

1. Generic is a new technology in JDK1.5. The emergence of new technologies aims to solve problems.

2. Generics can be used to identify the types of elements stored in a collection.

ArrayList
 
  
Al = new ArrayList
  
   
(); Al. add ("abc"); // correct // al. add (3); // an error is reported directly during compilation. // add the generic type to the Iterator. When the following code is obtained, the Iterator cannot be converted.
   
    
It = al. iterator (); while (it. hasNext () {// do not use strong conversion here, because the StringString str = it is definitely taken from it. next (); System. out. println (str );}
   
  
 

3. Benefits

(1) Run Time Problem ClassCastException to the compilation period.

(2) This avoids the trouble of forced conversion.

4. When will generics be used?

When the referenced data type of the operation is uncertain, you can use the generic type to write the referenced data type to be operated in <>. In fact, <> is a parameter range used to receive specific referenced data types.

In a program, as long as a type or interface with <> is used, it is necessary to specify the specific reference data type passed in.

You can also accept multiple data types at the same time:

class Tool
 
  Tool
  
    t = new Tool
   
    ();
   
  
 
18-2, generic-erasure & Compensation

1. Generics solve the security issues during the compilation period and are the technology used by the compiler.

2. During the runtime, the generic type is removed. The generated class file does not carry a generic type. This is called a generic erasure.

Why is it erased?

To be compatible with the class loaders during runtime, because generics are a new feature of JDK1.5, the class loaders will not recognize the class loaders if they are added to the class file, if you want the class loader to understand the generic type, the class loader should also be upgraded. To avoid the trouble of upgrading the class loader, the generic type will be handled by the compiler and will be deleted after compilation, so that the previous class loader can run it.

3. Generic compensation:

After erasure, do I need to add a strong rotation if I take out a value for the element, for example, String str = it. next? The answer is no. First, adding generics and compiling can ensure that the data in the set is of the specified type. Therefore, no elements other than the specified type will appear. In fact, a step-by-step action is automatically added during running. You can use the getClass () method to obtain the element type and then perform a conversion operation on it, so that you do not need to force the conversion.

18-3, generic-application in the Set

1. Take TreeSet as an example. TreeSet has a comparison function, but the stored type must implement the Comparable interface and the compareTo method in it. Or define a comparator, you can also implement the Comparator interface and the compare method. When you define a TreeSet, if you do not add generic Eclipse or other ides, there will be a yellow wave line prompt. With the wildcard, the yellow Wave Line will disappear.

2. When the Person class mentioned in the previous chapter implements the Comparable interface, the Comparable interface also needs to specify the generic type, for example: Comparable After this parameter is specified, the parameters in the overwriting compareTo method can be left empty of the Object. You can directly write the Person parameter, and the code in the method body does not need to be forced to perform a downward transformation. The Comparator interface must also be generic. The two parameters of the compare method in the Comparator interface can be directly accepted by the Person type. For example:

Class Person implements Comparable
 
  
{... Code... public int compareTo (Person p) {// Person p = (Person) p; // strong conversion can be omitted because generic int temp = this is defined. age = p. age; return temp = 0? This. name. compareTo (p. name): temp;}... code ...}
 
18-4, generic class

1. previously defined the tool class as follows:

public class Tool {private Object object;public Object getObject() {return object;}public void setObject(Object object) {this.object = object;}}

When other classes use this tool class, you can do this:

Tool tool = new Tool ();/* It is incorrect because there is no Worker class. Worker is the input error value, but compilation does not report an error. Because the Tool receives the Object type, the following statements must be strongly converted to match the type, because the Worker is upgraded to the Object type. */Tool. setObject (new Worker (); Student stu = (Student) tool. getObject ();

The tool class is for all types, and any class is a subclass of the Object. Therefore, according to the characteristics of polymorphism, by defining parameters as objects, we can make this method receive all types of parameters, we can only do this without generics.

After JDK1.5, the generic type is used to receive the referenced data type to be operated in the class. This is a generic type.

When Will generic classes be used?

When the referenced data types of operations in the class are uncertain, they are represented by generics.

For example:

public class Tool {private  Q q;public Q getObect() {return q;}public void setObject(Q object) {this.q = object;}}

With generics, you can do this when other classes use tool classes:

Tool
 
  
Tool = new Tool
  
   
(); // Tool. setObject (new Worker (); // an error is reported during compilation. The Student specified by the generic type cannot be entered. Tool. setObject (new Student (); Student stu = tool. getObject ();
  
 

18-5, generic Method

1. Add the generic method to the Tool class with generics in 18-4.

Public class Tool{Private Q q; public Q getObect () {return q;} public void setObject (Q object) {this. q = object;}/* If the method is not generic, an error will be reported, because the Tool explicitly only accepts the QQ type, so W type cannot be operated. To have one method operate W type, the generic type must be added before the return value type.
  
   
. */Public
   
    
Void show (W str) {System. out. println ("show" + str. toString ();}/* In addition, print receives a string. Can I print the length of the string? The answer is no, because QQ str = "abc" (Here we assume that abc is passed in), "abc" is upgraded to QQ type, the QQ type does not know the special method length () in the String type, so it cannot be printed. However, because QQ also inherits from the Object, you can use the method in the Object. */Public void print (QQ str) {System. out. println ("print" + str );}}
   
  

When calling:

Tool
 
  
Tool = new Tool
  
   
(); Tool. show (new Integer (4); // because show adds generics, it can accept types other than String defined by Tool. Tool. show ("abc"); // conforms to the generic type of the Tool. Tool. print ("haha"); // The print method does not have a wildcard type and is directly matched.
  
 

2. When the method is static, the generic type defined on the generic class cannot be used. If the static method is generic, the generic type can only be defined on the method.

If Definition method:

// If this method does not contain generics, the Y obj parameter will generate an error. The generics need to be clear by the object. // For example, Tool
 
  
Tool = new Tool
  
   
(); Static does not require objects, so you must add a generic type before void. Public static
   
    
Void method (Y obj) {System. out. println ("method" + obj );}
   
  
 

When calling this method:

Tool.method("bcd");//bcdTool.method(new Integer(9));//9

18-6, generic interface

1. Generic interfaces are defined on interfaces.

// The specific type is not clearly defined when defining the generic type. objects of any specified type can be accepted, which are clearly specified when an object is created. Interface Inter
 
  
{Public void show (T t);} // you can specify the type of the operation to be performed on the implemented interface. You can add the generic type of the specified type to this class. Class ImterImpl
  
   
Implements Inter
   
    
{Public void show (String str) {System. out. println ("show:" + str );}}
   
  
 

When calling the show method:

InterImpl in = new InterImpl (); // you do not need to add generics to the new object. In. show ("abc"); // call this operation.

2. the type still cannot be explicitly used in the class implementing the interface:

class InterImpl implements Inter {public void show(Q q) {System.out.println("show:" + q);}}

The type that can be explicitly used when the InterImpl class is new is defined as the above, and its generic type is further clarified when the new object is created.

InterImpl
 
   in = new InterImpl
  
   ();in.show(5);
  
 

In this way, the in object can only receive Integer objects.

18-7: generic definition-Upper Limit

1. There are multiple sets. If you want to use Iterator to retrieve data from multiple sets, do not define multiple Iterator. To improve code reusability, you must define a separate method for iteration. For example, there are two sets:

ArrayList Al = newArrayList ();

ArrayList Al 2 = newArrayList ();

If data already exists in these two sets, You need to extract the data and define an iteration method:

// Collection is received here, so you can iterate all sets such as List and Set, but the generic type is also defined here, so you can only accept String. Public static void printCollection (Collection
 
  
Al) {Iterator
  
   
It = al. iterator (); while (it. hasNext () {System. out. println (it. next ());}}
  
 

This is because the element types in the receiving set are uncertain. How can we receive different types of elements? You can use wildcard characters.

2. wildcard ---?, Unknown type.

Public static void printCollection (Collection
 Al) {Iterator
 It = al. iterator (); while (it. hasNext () {// you can use it. next () directly because the parameter type is unknown. System. out. println (it. next ());}}

You can also add generics to the method:

public static 
 
   void printCollection(Collection
  
    al)Iterator
   
     it = al.iterator();while(it.hasNext()) {T str = it.next();System.out.println(str);}
   
  
 

However, this is troublesome. But there are also other advantages, if you write this:

public static 
 
   T printCollection(Collection
  
    al) {Iterator
   
     it = al.iterator();T t = it.next();return t;}
   
  
 

In this way, the incoming T can be returned and operated, but the wildcard character --? is used --?.

3. Requirement: In an iteration method, only the Person and its subclass can be received.

Analysis: first? It won't work, because it cannot accept all objects.

For example, the Child classes of Person include Worker and Student. To iterate these two classes but not those other than Person (such as String), you can write them as follows:

//
 The generic definition is all types that inherit the Person type or the Person type public static void printCollection (Collection
 Al) {Iterator
 It = al. iterator (); while (it. hasNext () {Person p = it. next (); // You can explicitly accept the Person or its subclass System. out. println (p. getName () + ":" + p. getAge ());}}

If you want to use this method to iterate on objects of the String type, an error will be reported during compilation. Because String is not a subclass of Person, this is the upper limit of generics. In fact, generic writing Yes .

18-8, lower limit

1. Definition method: Indicates that the specified type must be the parent class of E or E.

For example, Student and Worker are both child classes of Person,

Three sets are defined:

ArrayList
 
   al1 = new ArrayList
  
   ();ArrayList
   
     al2 = new ArrayList
    
     ();ArrayList
     
       al3 = new ArrayList
      
       ();
      
     
    
   
  
 

Then define a method:

public static void printCollection(Collection
  al) {Iterator
  it = al.iterator();while(it.hasNext()) {System.out.println(it.next());}}

At this time, the method of an iterative set element refers to the parent class of Student or Student. Because Student inherits from Person, Worker also inherits from Person, therefore, if a Worker is input, an error is returned. This is the lower limit of the generic type.

18-9: Tips for using the set

1. Do geometric elements need to be unique?

| -- Required: Use Set

| -- Do I need to specify the order?

| -- Required: TreeSet

| -- Not required: HashSet

| -- But you want a sequence consistent with the storage: orders hashset

| -- Not required: Use List

| -- Do I need to add or delete files frequently?

| -- Required: required list

| -- Not required: ArrayList

2. How do I remember the structure and system of each container? Look at the name!

List

| -- ArrayList

| -- Upload list

Set

| -- HashSet

| -- TreeSet

The suffix is the system to which the set belongs.

The prefix name is the data structure of the set.

When you see an array, you must think of an array. The query is fast and has a badge.

Link: You need to think of the linked list, add, delete, and add, get, and remove methods.

When we see hash, we need to think of a hash table. uniqueness requires that elements overwrite the hashCode and equals methods.

Tree: Binary tree, sort, and Comparable.

Generally, these common collection containers are not synchronized.

18-10, tool class-Collections sorting

1. java. util. Collections

This class is completely composed of static methods that operate on the Collection or return the Collection.

2. Collections is a work class of the Collection framework, and the methods in it are static.

Static > Voidsort (List List)

Sort the specified list in ascending order based on the natural sorting of elements. All elements in the list must implement the Comparable interface. All elements in the list must be Comparable to each other, that is, the types must match each other.

Demo sorting method example:

Public static void demo_1 () {List
 
  
List = new ArrayList
  
   
(); List. add ("abcde"); list. add ("CBA"); list. add ("aa"); list. add ("zzz"); list. add ("CBA"); list. add ("nbaa"); System. out. println (list); // sort Collections. sort (list); // String implements the Comparable interface, which is Comparable to System. out. println (list );}
  
 

To sort by length, you can use sort (List List, Comparator C) Implement the sort method with a Comparator. This requires defining a class, implementing the Comparator interface, and implementing the compare method. For example:

public class ComparatorByLength implements Comarator
 
   {public int compare(String o1,String o2) {int temp = o1.length() - o2.length();return temp == 0 ? o1.compareTo(o2) : temp;}}
 

Call the methods Collections. sort (list, newComparatorByLength.

18-11, half & maximum

1, static Int binarySearch (List > List, T key)

This method uses the Binary Search Method to search for the specified list to obtain the specified object. Before this call, you must sort the list in ascending order according to the natural order of the list elements, it is actually the binary search method.

2, static Int binarySearch (List List, T key, Comparator C)

The difference from the above method is that the elements in the set are sorted in ascending order by the specified comparator.

3, half:

Public class Demo {public static void main (String [] args) {List
 
  
List = new ArrayList
  
   
(); List. add ("abcde"); list. add ("CBA"); list. add ("aa"); list. add ("zzz"); list. add ("CBA"); list. add ("nbaa"); // sort Collections. sort (list); int index = Collections. binarySearch (list, "CBA"); // The index is 2 }}
  
 

4. Maximum Value

Static T max (Collection Coll)

Return the maximum element of a given collection according to the natural order of the elements. The elements in the collection must have the comparison function. This method is based on Comparable comparison.

Static T max (Collection Coll, Comparator Comp)

Returns the maximum value of a given collection based on the Generation sequence of the specified comparator.

For example:

String max = Collections. max (list, newComparatorByLength ())

Returns the longest string.

18-12, Reverse Order & replacement

1, static Comparator ReverseOrder ()

Returns a comparator that forcibly reverses the natural order of objects in the collection of the Comparable interface, which is compared according to Comparable.

TreeSet Ts = new TreeSet (Collections. reverseOrder (newComparatorByLength ()))

This method forcibly reverses the comparator to specify the reverse after sorting.

2. Replace

Public class Demo {public static void main (String [] args) {List
 
  
List = new ArrayList
  
   
(); List. add ("abcde"); list. add ("CBA"); list. add ("aa"); // Replace "CBA" in the list set with "nba" // principle: list. set (indexOf ("CBA"), "nba") Collections. replaceAll (list, "CBA", "nba ");}}
  
 

18-13. Other methods are used to convert a non-synchronous set to a synchronous set.

1. fill Method. All values in the set can be re-assigned (re-initialized)

Public class Demo {public static void main (String [] args) {List
 
  
List = new ArrayList
  
   
(); List. add ("abcde"); list. add ("CBA"); list. add ("aa"); Collections. fill (list, "cc"); System. out. println (list); // [cc, cc, cc] initializes all elements as cc }}
  
 

2. Collections. shuffle (list); // sorts the elements in the set randomly.

3, static ArrayList List (Enumeration E)

Returns an array list that contains the elements returned by the specified enumeration in the returned order and converts the enumeration to an ArrayList.

4, static Enumeration Enumeration (Collection C)

Converts a specified set to an enumeration.

5, static Enumeration SynchronizedList (List List)

Returns the list supported by the specified list (thread-safe.

In addition, you can convert Collection, Map, Set, and so on to thread-safe.

Implementation principle:

List list = new ArrayList (); // non-synchronous

List = MyCollections. synList (list); // returns a synchronized list.

Lock a non-synchronous set:

// Ensure that you cannot delete the object when adding the object. When you delete the object, you cannot add class MyCollections {public static List synList (List list) {return new MyList (list );} private class MyList implements List {private List list; private static final Object lock = new Object (); MyList (List list) {this. list = list;} public boolean add (Object obj) {synchronized (lock) {return list. add (obj) ;}} public boolean remove (Object obj) {synchronized (lock) {return list. remove (obj );}}}}

18-14, Arrays array tool Class Method Introduction

1. binarySearch (...) binary search method returns an index.

2. equals (...) overwrites the equals in the Object, and compares whether the content is the same, that is, the length is the same and the elements on the corresponding bit are the same.

3. static void fill (byte [] a, byte val) assigns val to every position in byte.

4. sort (...) sorts the input array.

5. toString () overwrites the toString () in the Object and directly prints the elements in the array.

6. Classic Implementation of toString:

public static String myToString(int[] a) {int iMax = a.length - 1;if(iMax == -1) {return "[]";}StringBuilder b = new StringBuilder();b.append('[');for(int i=0;;i++) {b.append(a[i]);if(i == iMax) {return b.append(']').toString();}b.append(",");}}

18-15, Arrays-asList Method

1, static List AsList (T...)

Returns a list of fixed sizes supported by the specified array.

The reason for using asList: the methods provided in Arrays are also quite limited. It is much easier to convert an array into a set, for example, to determine whether an element is in an array, if Arrays does not use this method, you need to write a judgment method by yourself. However, if you convert the array into a List, you can use contains to judge the method.

2. Benefit: You can use the methods in the set to operate the elements in the array.

Note: The length of the array is fixed, so the addition and deletion methods of the set cannot be used. Otherwise, the UnsupportedOperationException will occur, as long as the length of the set is not changed, the method can be used.

However, you can use the set method to replace the specified element with the specified element.

3. If the elements in the array are objects, the elements in the array are directly stored as the elements in the set when converted to a set. If the data in the array is of the basic data type, the array is stored as an element in the set.

For example:

Int [] arr = {31,11, 51,61 };

List List = Arrays. asList (arr );

System. out. prtinln (list); // [[I @ C17164

In this case, the length of the list set is 1, and the printed result is an array object.

However, if you define an Integer array, that is, an array of non-basic data types:

Integer [] arr = {31,11, 51,61 };

List List = Arrays. asList (arr );

System. out. println (list); // print [,]

NOTE: If non-basic data type data is stored, the toString () of each object is printed ().

18-16, Collection --> toArray Method

1. How to convert a set into an array?

The toArray method in the Collection interface is used.

2. convert a set to an array: You can limit the operation methods of elements in the Set, and do not allow addition or deletion.

3. The toArray method needs to input an array of the specified type.

How to define the length?

If the length is smaller than the size of the set, this method creates an array of the same type and the same size as the set.

If the length is greater than the size of the set, this method uses the specified array to store the elements of the set. The default value for other positions is null.

We recommend that you specify the length as the size of the set.

List
 
   list = new ArrayList
  
   ();list.add("abc1");list.add("abc2");list.add("abc3");String[] arr = list.toArray(new String[list.size()]);System.out.println(Arrays.toString(arr));
  
 

18-17, JDK1.5 new feature-ForEach Loop

1. The parent interface of Collection is the Iterable interface. Only one iterator method exists in JDK1.5, because the top-level parent class like Collection may appear in the future, they all hope they have the iteration function, so the extraction improves the scalability.

2. ForEach loop, enhanced For Loop

Format: for (type variable: Collection set or array ){...}

Differences between traditional for and advanced:

(1) traditional for statements can be executed many times, because it can define the increment and condition of the control loop.

(2) advanced for is a simplified form, which must have the target to be traversed. The target is either an array or a Collection of single columns.

To retrieve only elements in an array, use advanced.

If you want to operate the badge of an array, we recommend that you use traditional.

Can I use advanced for to traverse map sets?

It cannot be used directly, but map can be converted into a single column set.

4. Example:

Public class Demo1 {public static void main (String [] args) {List
 
  
List = new ArrayList
  
   
(); List. add ("abc1"); list. add ("abc2"); list. add ("abc3"); for (String s: list) {// simplifies writing. The bottom layer is actually iteratorSystem. out. println (s );}}}
  
 

public class Demo2 {public static void main(String[] args) {int[] arr = {3,1,5,7,4};for(int i : arr) {System.out.println(i);}}}

Example of traversing a Map:

public class Demo3 {public static void main(String[] args) {Map
 
   map = new HashMap
  
   ();map.put(3,"zhangsan");map.put(1,"wangyi");map.put(5,"wangcai");map.put(7,"xiaoqiang");for(Integer key : map.keySet()) {String value = map.getKey();System.out.println(key + "::" + value);}for(Map.Entry
   
     me : map.entrySet()) {Integer key = me.getKey();String value = me.getValue();System.out.println(key + ":" + value);}}}
   
  
 

18-18, new features of JDK1.5-variable parameters of functions

1 is actually an array, but it receives elements of an array. These elements are automatically encapsulated into arrays. This simplifies the writing of callers.

Note: variable parameter types must be defined at the end of the parameter list.

Public static newAdd (int... arr) {int sum = 0; for (int I = 0; I

Note:

Public static newAdd (int... arr, int)

{... Code...} // incorrect syntax. All input parameters are assigned to arr, And a has no value.

Public static newAdd (int a, int... arr)

{... Code...} // The statement is correct. The first value is passed to a, and the subsequent value is sent to arr.

18-19, JDK1.5 new feature-static Import

Static import is actually a static member of the imported class.

Add static after import, for example:

Import java. util. arrayList; import java. util. collections; import static java. util. collections. *; // import all static members in Collections to simplify the writing of import static java. lang. system. *; // import all static members in the System public class Demo {public static void main (String [] args) {List
  
   
List = new ArrayList
   
    
(); List. add ("abc3"); list. add ("abc7"); list. add ("abc1"); out. println (list); // out is a static member of the System class. After static import to System, you do not need to call the static method out in sort (list) through System; // Collections. println (list); String max = max (list); // The static method out in Collections. println ("max =" + max );}}
   
  


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.