Java Chapter Thirteen: Enumerated Types and Generics

Enumeration type

Use enumeration types to set constants

When setting constants, we usually place them in the interface so that they can be used directly in the program. This constant cannot be modified because when the constant is defined in the interface, the modifiers of the constant are changed to final and static. The general code for defining constants is as follows:

interface SeasonInterface{

final int spring=1;

final int summer=2;

final int autumn=3;

final int winter=4;

}

After the emergence of enumeration types, they gradually replaced the above constant definition method. code show as below:

public enum SeasonEnum {

spring,

summer,

autumn,

winter;

}

code show as below:

interface SeasonInterface{//Four Seasons Interface
final int spring=1;
final int summer=2;
final int autumn=3;
final int winter=4;
 
enum SeasonEnum{//Four Seasons Enumeration
    spring,
    summer,
    autumn,
    winter,
}
 
public class SeasonDemo {
public static void printSeason1(int temp){
switch(temp){
case SeasonInterface.spring:
System.out.println("This is spring");
break;
case SeasonInterface.summer:
System.out.println("This is summer");
break;
case SeasonInterface.autumn:
System.out.println("This is autumn");
break;
case SeasonInterface.winter:
System.out.println("This is winter");
break;
default:
System.out.println("Encoding error");
break;
}
}
public static void printSeason2(SeasonEnum seasonEnum) {
switch(seasonEnum) {
case spring:
System.out.println("This is spring");
break;
case summer:
System.out.println("This is summer");
break;
case autumn:
System.out.println("This is autumn");
break;
winter case:
System.out.println("This is winter");
break;
default:
System.out.println("Encoding error");
break;
}
}
public static void main(String[] args) {
printSeason1(2);//Use interface constants as parameters
printSeason2(SeasonEnum.spring);//Use enumeration types as parameters, only the values in the enumeration can be used
}
}

The running results are as follows:

In-depth understanding of enumeration types

1. values() method

Enumeration type instance, this method returns all enumeration values in the enumeration in the form of an array.

code show as below:

enum SeasonEnum{
   spring,
    summer,
    autumn,
    winter,
}
 
public class SeasonDemo {
public static void main(String[] args) {
SeasonEnum[] seasons=SeasonEnum.values();
for(SeasonEnum temp:seasons) {
System.out.println(temp + "is the number" + (temp.ordinal() + 1) + "number");
}
}
}

The running results are as follows:

2. valuesOf() method and compareTo() method

The static method valuesOf() in enumeration types can convert ordinary strings to enumeration types, while the comparedTo() method is used to compare the order in which two enumeration type objects are defined.

3. ordinal() method

The ordinal() method in an enumeration type is used to obtain the position index value of an enumeration object.

4. Constructor methods in enumeration types

In an enumeration type, you can add a constructor, but it is stipulated that this constructor must be modified by the private modifier.

code show as below:

enum SeasonEnum {//Four Seasons Enumeration
spring("All things revive"),
summer("scorching sun"),
autumn ("high autumn air"),
winter("snowy");
 
private String introduce;//Remarks on enumeration
 
 
private SeasonEnum(String introduce) {//Construction method
System.out.println("This is" + " " + this.toString() + ", after I come" + introduce);
}
public String getIntroduce() {//Get the introduction value
return introduce;
}
}
 
 
public class SeasonDemo {
public static void main(String[] args) {
SeasonEnum[] seasons=SeasonEnum.values();
for(SeasonEnum temp:seasons) {
System.out.println(temp + "is the number" + (temp.ordinal() + 1) + "number");
}
}
}

The running results are as follows:

Advantages of using enumerated types

Enumerated type declarations provide a user-friendly way to define variables that enumerate all possible values of a certain data type. To summarize the enumeration type, it has the following characteristics:

  • Type safety.
  • Compact and efficient data definition.
  • Can interact perfectly with other parts of the program.
  • High operating efficiency.

Generics

Define generic classes

The top-level parent class of the Object class. In order to be more versatile, many programmers usually design programs so that the values passed in and the values returned are mainly of the Object type. When these instances need to be used, the instance must be correctly converted to the original type, otherwise a ClassCastException will occur at runtime.

In order to prevent this kind of problem in advance, Java provides a generic mechanism. The syntax is as follows:

Class name.

public class Book<T> { //Define the Book<T> class with generics
private T booklnfo; //Type parameter: book information
public Book(T booklnfo) { //Constructor whose parameters are type parameters
this.booklnfo= booklnfo; //Assign value to book information
}
public T getBooklnfo() { //Get the value of book information
return booklnfo;
}
public static void main(String[] args) {
//Create a book title object whose parameter is String type
Book<String>bookName = new Book<String>(""Java from Beginner to Master");
//Create an author object whose parameter is String type
Book<String>bookAuthor = new Book<String>("Tomorrow Technology");
//Create a price object whose parameter is Double type
Book<Double>bookPrice = new Book<Double>(69.8);
//Create bonus source code with parameters of Boolean type
Book<Boolean>hasSource = new Book<Boolean>(true);
//The console outputs the book title, author, price and whether it comes with a CD
System.out.println("Book name: " + bookName.getBooklnfo());
System.out.println("Author: " + bookAuthor.getBooklnfo());
System.out.println("Price: " + bookPrice.getBooklnfo());
System.out.println("Is the source code included?" + hasSource.getBooklnfo());
\t\t\t
}
 
}

The running results are as follows:

General usage of generics

1. Declare multiple types when defining a generic class

The syntax is as follows:

class MyClass{ }

2. Declare the array type when defining a generic class

Case code:

public class ArrayClass<T> {
private T[] array; //Define a generic array
public T[] getArray() {
return array;
}
public void setArray(T[] array) {
this.array = array;
}
public static void main(String[] args) {
ArrayClass<String> demo = new ArrayClass<String>();
String value[] = {"Member 1", "Member 2", "Member 3", "Member 4", "Member 5"};
demo.setArray(value);
String array[] = demo.getArray();
for(int i = 0;i<array.length;i + + ) {
System.out.println(array[i]);
}
}
 
}

The running results are as follows:

Advanced usage of generics

1. Limit the available types of generics

By default, any type can be used to instantiate a generic class object, but Java also imposes restrictions on the types of generic class instances.

The syntax is as follows:

class class name

anyClas refers to an interface or class. After using generic restrictions, the type of the generic class must implement or inherit the anyClass interface or class. Regardless of whether anyClass is an interface or a class, the extends keyword must be used when making generic restrictions.

2. Use type wildcards

In the generic mechanism, type wildcards are provided, whose main function is to restrict the type of the generic class to implement or inherit a certain interface or subclass when creating a generic class object. To declare such an object, you can use the “?” wildcard to represent it, and use the extends keyword to restrict the generic type.

The syntax for using generic type wildcards is as follows:

Generic class namea=null;

3. Inherit generic classes and actual generic interfaces

Classes and interfaces that define generics can be inherited and implemented. Let the SubClass class inherit the generic type of ExtendClass. The code is as follows:

class ExtendClass{}

class SubClassimplements SomeInterface{}

Summary

How to use generics:

  • The type parameters of generics can only be class types, not simple types. A generic definition such as A is wrong.
  • The number of generic types can be multiple
  • You can use the extends keyword to limit the types of generics
  • You can use wildcards to limit the types of generics