Java Career - High Technology - Enumeration and Part of JDK 1.5 New Features

Keywords: Java JDK Attribute

Lecture 1 Enumeration

I. overview

Enumeration here is not a unique enumeration iterator for collection vector s, but a new feature of JDK 1.5. The reason for using it alone is that this knowledge point is more important and relatively difficult to understand.

Why do we have enumerations?

Question: What is the definition of a week or gender variable? Assume that Monday to Sunday is represented by 1-7, but someone might write int weekday = 0, or that even using constants can't prevent accidents.

Enumeration means that the value of a variable of a certain type can only be one of several fixed values, otherwise the compiler will report an error. Enumeration allows the compiler to control the illegal values filled in the source program at compile time, which can not be achieved in the development stage in the way of ordinary variables.

Example:

  1. /* 
  2.  * How to implement the enumeration function with ordinary classes, and define a Weekday class to simulate the enumeration function.   
  3.     1,Private Construction Method 
  4.     2,Each element is represented by a public static member variable 
  5.     3,There can be several public or abstract methods. Defining nextDay in an abstract way transforms a large number of if.else statements into separate classes. 
  6.  
  7. */  
  8.   
  9. package cn.itheima;  
  10.   
  11. public abstract class WeekDay {  
  12.     private WeekDay(){}  
  13.   
  14.     public final static WeekDay SUN=new WeekDay(){  
  15.         public WeekDay nextDay(){  
  16.             return MON;  
  17.         }  
  18.     };  
  19.       
  20.     public final static WeekDay MON=new WeekDay(){  
  21.         public WeekDay nextDay(){  
  22.             return SUN;  
  23.         }  
  24.     };  
  25.       
  26.     public abstract WeekDay nextDay();  
  27.   
  28.     public String toString(){  
  29.         return this==SUN?"SUM":"MON";  
  30.     }  
  31. }  


II. Basic Applications of Enumeration

1. Enumeration class is defined by enum keyword. Enumeration class is a special class. Each element is an instance object of this class.

2. Use enumeration classes to specify values, such as the WeekDay class above. Later, the values defined with this type can only be those specified in this class. If they were not, the compiler would not pass.

3. Benefits: Errors are found at compile time, indicating that the values do not match, reducing runtime errors.

4. If the caller wants to print information about the elements in the enumeration class, it is up to the person who wrote the class to define the toString method.

Note: The enumeration class is a class and is an inheritable final class, in which the elements are static constants of the class.

5. Common methods:

Constructor:

1) The constructor is invoked only when an enumeration value is constructed.

2) Constructors are private only, and public constructors are never allowed. This ensures that external code cannot reconstruct instances of enumerated classes. Because the enumeration value is public static final constants, but methods and data domains of enumerated classes can be accessed externally.

3) The constructor can have more than one, which call initializes the corresponding value.

Non-static methods: (All enumeration classes inherit the Enum method)

1) String to String (); // Return the name of the enumerator

2) int ordinal(); //Return the order of enumeration values in the enumeration class, in the order defined

3) Class getClass(); get the corresponding class name

4) String name(); // Returns the name of this enumeration constant and declares it in its enumeration declaration.

Static method:

ValueOf (String); // to the corresponding enumeration object, that is, to convert a string to an object

2) values(); // Get all enumerated object elements

Example:

  1. package cn.itheima;  
  2.   
  3. public class EnumDemo {  
  4.     public static void main(String[] args) {  
  5.         WeekDay weekDay=WeekDay.MON;  
  6.         System.out.println(weekDay);//Output Enumeration Constant Name  
  7.         System.out.println(weekDay.name());//Output object name  
  8.         System.out.println(weekDay.getClass());//Output Correspondence Class  
  9.         System.out.println(weekDay.toString());//Output Enumeration Object Name  
  10.         System.out.println(weekDay.ordinal());//Output the order of this object in the enumeration constants  
  11.         System.out.println(WeekDay.valueOf("WED"));//Converting strings to enumeration constants  
  12.         System.out.println(WeekDay.values().length);//Get all the enumerated elements and print their length  
  13.     }  
  14.     //Define enumerated inner classes  
  15.     public enum WeekDay{  
  16.         SUN(1),MON,TUE,WED,THI,FRI,SAT;//Semi-colons are optional, but they cannot be omitted if there are methods or other members below.  
  17.         //And when there are other methods, they must be below these enumerated variables.  
  18.   
  19.         //Parametric constructor  
  20.         private WeekDay(){  
  21.             System.out.println("First");  
  22.         }  
  23.         //Constructor with parameters  
  24.         private WeekDay(int day){  
  25.             System.out.println("Second");  
  26.         }  
  27.     }  
  28. }  

 

Advanced Applications of Enumeration

1. Enumeration is equivalent to a class, in which construction methods, member variables, common methods and abstract methods can also be defined.

2. Enumeration elements must be located at the beginning of the enumeration body, and the list of enumerated elements must be separated by semicolons from other members. Place member methods or variables in the enumeration in front of the enumeration elements, and the compiler reports errors.

3. Enumeration of band construction methods

1) Construction methods must be defined as private

2) If there are multiple constructions, how to choose which one?

3) The enumeration elements MON and MON () have the same effect as calling the default construction method.

4. Enumeration with Method

Such as:

  1. /* 
  2.  * Abstract enumeration method 
  3.  * In this case, the constants in enumeration need to be implemented by subclasses, which can be defined by means of internal classes. 
  4.  * Enumeration with Method 
  5.     1)Define Enumeration TrafficLamp 
  6.     2)Implementing the Common next Method 
  7.     3)Implementing the abstract next method: Each element is an instance object generated by subclasses of the enumeration class, which are subclasses of the enumeration class. 
  8.     4)Definition is done in a manner similar to internal classes. 
  9.     5)Construction Method of Increasing Upper Representation Time 
  10.  * */  
  11.   
  12. package cn.itheima;  
  13.   
  14. public class EnumTest {  
  15.     public enum TrafficLamp{  
  16.         RED(30){  
  17.             public TrafficLamp nextLamp(){  
  18.                 return GREEN;  
  19.             }  
  20.         },  
  21.         GREEN(30){  
  22.             public TrafficLamp nextLamp(){  
  23.                 return YELLOW;  
  24.             }  
  25.         },  
  26.         YELLOW(5){  
  27.             public TrafficLamp nextLamp(){  
  28.                 return RED;  
  29.             }  
  30.         };  
  31.         private int time;  
  32.         //constructor  
  33.         private TrafficLamp(int time){  
  34.             this.time=time;}  
  35.         //Abstract method  
  36.         public abstract TrafficLamp nextLamp();  
  37.     }         
  38. }  

Summary:

1. Anonymous inner classes are common

2. The type returned by the method of the class can be the type of this class.

3. Static constants can be defined in classes, and the result of constants is their own instance objects of this type.

4. When enumeration has only one member, it can be implemented as a singleton.

Note:

1. All enumerations inherit from the java.lang.Enum class. Since Java does not support multiple inheritance, enumerated objects can no longer inherit other classes.

2. switch statements support int,char,enum types, and use enumerations to make our code more readable.

 

Lecture 2: New features for other parts of JDK 1.5

I. Static Import

1. Writing:

Import static java.util.Arrays. *; // Import is the static member of the class Arrays.

Import static java.lang.System. *// Imports all static members of the Ssytem class.

Classes are imported without static, and static imports are all static members of a class. This way, you can call the static method of the class without writing the class name. For example: Arrays. sort (array); you can write sort (array);

2. Attention:

When two imported classes have members of the same name, you need to add the corresponding class name before the members.

When class names are renamed, specific package names need to be specified. When a method is renamed, specify the specific object or class to which it belongs.

Example:

  1. import java.util.*;  
  2. import static java.util.Arrays.*;  
  3. import static java.lang.System.*;  
  4.   
  5. class  StaticImport //extends Object  
  6. {  
  7.     public static void main(String[] args)   
  8.     {  
  9.         out.println("haha");//Writing System can be omitted directly when printing out.  
  10.         int[] arr = {3,1,5};  
  11.   
  12.         sort(arr);//Writing Array can be omitted when using the method sort of the Array tool class.  
  13.   
  14.         int index = binarySearch(arr,1);//Half-point search can also be omitted  
  15.         out.println("Index="+index);  
  16.   
  17.         //When no inheritance is specified, the class inherits Object by default.  
  18.        //Because toString methods are available, specific callers must be written in order to distinguish between them.  
  19.        out.println(Arrays.toString(arr));  
  20.     }  
  21. }  

 

Enhance for cycle

1. Format:

For (data type variable name: collection or array traversed) {execution statement}

2, explain

A. Traversing the collection. Only collection elements can be retrieved. But collections cannot be manipulated. It can be seen as a short form of iterator.

b. In addition to traversing, the iterator can also perform the actions of elements in the remote collection. If you use ListIterator, you can also add, delete and modify the collection during traversal.

3. The difference between traditional for and advanced for:

Advanced for has one limitation. There must be a traversal target (collection or array).

Traditional for traverses arrays with indexes.

It is recommended that when traversing arrays, you still want to use traditional for. Because traditional for can define corner labels.

Note: Variable types can be preceded by modifiers such as final (accessible by local internal classes).

Example:

  1. import java.util.*;  
  2. class For  
  3. {  
  4.     public static void main(String[] args)   
  5.     {  
  6.         //Define an ArrayList collection  
  7.         ArrayList<String> al = new ArrayList<String>();  
  8.         al.add("abc1");  
  9.         al.add("abc2");  
  10.         al.add("abc3");  
  11.   
  12.         for(String s : al)  
  13.         {  
  14.             System.out.println(s);//Traversing sets with advanced for  
  15.         }  
  16.   
  17.         //Traditional for and advanced for traversal arrays  
  18.         int[] arr = {3,5,1};  
  19.   
  20.         for(int x=0; x<arr.length; x++)  
  21.         {  
  22.             System.out.println(arr[x]);  
  23.         }  
  24.         for(int i : arr)  
  25.         {  
  26.             System.out.println("i:"+i);  
  27.         }  
  28.   
  29.         //Define a HashMap collection  
  30.         HashMap<Integer,String> hm = new HashMap<Integer,String>();  
  31.   
  32.         hm.put(1,"a");  
  33.         hm.put(2,"b");  
  34.         hm.put(3,"c");  
  35.   
  36.         //Advanced for traversal for keySet extraction  
  37.         Set<Integer> keySet = hm.keySet();  
  38.         for(Integer i : keySet)  
  39.         {  
  40.             System.out.println(i+"::"+hm.get(i));  
  41.         }  
  42.   
  43.         //Advanced for traversal for entrySet fetching  
  44.         for(Map.Entry<Integer,String> me : hm.entrySet())  
  45.         {  
  46.             System.out.println(me.getKey()+"------"+me.getValue());  
  47.         }  
  48.   
  49.     }  
  50. }  

 

Variable parameters: (method overload) Variable parameters

If a method passes in multiple parameters in the parameter list and the number of parameters is uncertain, the method must be overridden each time. Arrays can then be used as formal parameters. But when it comes in, you need to define an array object each time as an actual parameter. After JDK version 1.5, a new feature is provided: variable parameters.

Use _____________ These three points are expressed, and the three points are between the variable type and the variable name, whether there are spaces or not.

Variable parameters are short form of array parameters. You don't need to manually create an array object every time. As long as the element to be operated on is passed as a parameter. These parameters are implicitly encapsulated into arrays.

Note when using: Variable parameters must be defined at the end of the parameter list.

Example:

  1. class  ParamMethodDemo  
  2. {  
  3.     public static void main(String[] args)   
  4.     {  
  5.         show("haha",2,3,4,5,6);  
  6.     }  
  7.     public static void show(String str,int... arr)//... is a variable parameter.  
  8.     {  
  9.         System.out.println(arr.length);  
  10.     }  
  11. }  

 

IV. Automatic Unpacking and Packing of Basic Data Types

1. Automatic packing: Integer iObj = 3;

2. Automatic unpacking: iObj + 2;

3. For the description of basic data types: integers between - 128 and 127 are packaged as Integer objects, which are stored in the constant pool cache. When an object is created, if its value is in this range, it will be directly found in the constant pool. Because these small values are used frequently, it is much easier to cache in the constant pool when they are called.

4. flyweight:

Summary: There are many small objects with many identical attributes, which change the same part of the attributes into the same object. These attributes are called internal state. The different attributes turn them into parameters of the method, called external states. This memory optimization only creates a pattern of objects, called the hedonic pattern. For example: Integer objects with values ranging from - 128 to 127 have the same values. Because these small numbers are cached in a pool and are called more frequently, they are usually fetched in the pool, which leads to the same objects. This is the typical hedonic design pattern.

2) Application:

(1) The input of English letters in word can create 26 objects, each of which has a different location (coordinates), so an object can be used to call the location method: for example, the letter i: i.display(intx,inty), encapsulating the highly reusable letter I of char type into an object.

(2) Icon: The folder icon under window s, only the name of this attribute is different, contains many other identical properties, then you can apply the hedge mode.

valueOf(int x): A static method in Integer that converts an integer to Integer, i.e. converts the basic data type to a wrapper class.

Posted by eerok on Thu, 18 Apr 2019 13:15:35 -0700