Java generics (defines classes and methods)

About the grammar for defining Java generic classes and methods. See here for terms → Points of Java Generics

Temporary parameters

For example, if `` `List , then Eenclosed in angle brackets is the pseudo parameter. In terms of grammar, there is no problem with two or more characters or mixed lowercase letters, but by convention, one character is often used.Or```EachelementOrtypeIt is an abbreviation for.

Constraints on formal parameters

There are some restrictions because the type parameter information is cleared at run time. -- new T () `` `cannot be done -- new T [] `` `cannot be done -- T.class cannot be referenced --obj instance of T cannot be evaluated

How to define a generic class

If you write `SomeClass <T> ```, you can use its type parameter `T``` in the fields of the class and in the methods (including arguments and return values).

//↓ Write the type parameter here
public class SomeClass<T> {
  private T t;
  private List<T> list = new ArrayList<T>();
  public void set(T arg){
    this.t = arg;
  }
  public T get(){
    return this.t;
  }
}

Note that the formal parameters of a generic class cannot be used in static methods or static statements in that class as shown below.

public class Hoge<T>{
  static {
    T t; //Compile error
  }
  public static void hoge(T t){ //Compile error
  }
}

How to define a generic method

If you write `<T>` before the return type of a method, you can use its type parameter `` `T``` in the method.

  //↓ Write the type parameter here
  public static <T> ArrayList<T> someMethod(T arg){
    ArrayList<T> list = new ArrayList<T>();
    list.add(arg);
    return list;
  }

That's all for the basics of generic class definition and method definition, and then we will change the contents of the pseudo parameter `<T>` depending on the case.


Multiple type parameters

You can use multiple type parameters separated by commas.

  public static <K, V> HashMap<K, V> newHashMap(){
    return new HashMap<K, V>();
  }
  // ※<K,V>The type of is guessed from the left side
  Map<String, Integer> map = newHashMap();

Boundary parameters

<t extends classes and interfaces>If you write liketCan require the caller to be a subclass of the specified class (or the specified class itself).

  //ArrayList that can only be instantiated with a Subclass of Number type or Number type
  public class NumArrayList<T extends Number> extends ArrayList<T> {}
  List<Number> numberList = new NumArrayList<Number>(); // ok
  List<Double> doubleList = new NumArrayList<Double>(); // ok
  List<String> stringList = new NumArrayList<String>(); //Compile error

Recursive boundary

This example requires the caller that E is an implementation class of Comparable .

  //Method to retrieve maximum value from collection
  public static <E extends Comparable<E>> E max(Collection<E> collection) {
    //Code omitted. E is compareTo(E)Because it has a method
    //You can use it to implement an algorithm to find the maximum value of an element.
  }

Multiple inheritance specifications

To specify that it is an implementation class of multiple interfaces, connect the parent class and interfaces with `&`.

//Requires E to implement both Comparable and Serializable interfaces
public class Fuga<E extends Comparable<E> & Serializable>{}

("& ``` Is a very unfamiliar symbol, but I'm using ``` & ``because ```, `` `is already used as the type parameter delimiter. I think that the)

Recommended Posts

Java generics (defines classes and methods)
[Java] Generics classes and generics methods
Java abstract methods and classes
Java programming (classes and instances, main methods)
java (classes and instances)
[Java] Personal summary of classes and methods (basic)
(Note) Java classes / variables / methods
Java methods and method overloads
java Generics T and? Difference
[Ruby] Singular methods and singular classes
Ruby methods and classes (basic)
[Ruby] Singular methods and singular classes
Java methods
How to call classes and methods
Java methods
Studying Java 8 (StaticIF and Default methods)
[Java] Generics
Classes and instances Java for beginners
[Java ~ Classes and External Libraries ~] Study Memo (6)
Classes and instances
Java class methods
Java Generics Summary
[Java] Generics sample
Java Generics (Notes)
Functions and methods
Java and JavaScript
XXE and Java
Differences in writing Java, C # and Javascript classes
Kantai Collection Java # 1 Classes and Objects [For Beginners]
Check static and public behavior in Java methods
How to access Java Private methods and fields
[Ruby] Classes and instances
java classes, instances, objects
HashMap and HashSet classes
Java true and false
[Java] String comparison and && and ||
[Java] About anonymous classes
Frequently used Java generics
Ruby classes and instances
Java --Serialization and Deserialization
Java classes and instances to understand in the figure
Ruby variables and methods
timedatectl and Java TimeZone
[Java] Branch and repeat
List and happy classes
Equivalence comparison of Java wrapper classes and primitive types
[Java] Variables and types
[Java10] Be careful of using var and generics together
[Java] Overload and override
Define abstract methods in Java enum and write each behavior
Think about the differences between functions and methods (in Java)
ClassCastException occurs when migrating from Java7 to Java8 ~ Generics and overload ~
Java Beginner Escape Boot Camp Part 2 Understanding Java Classes and Encapsulation
Study Java # 2 (\ mark and operator)
Java version 8 and later features
Coding methods and refactoring principles
[Java] Difference between == and equals
Java programming (variables and data)
Java and Iterator Part 1 External Iterator
rails path and url methods
Java if and switch statements