java Generic Programming

What is Generic Programming?

When programming, I want to implement classes and methods with multiple types. It's easy to see, for example, that it's ridiculous to implement an ArrayList for an int, a double for a String, respectively. ArrrayList \ <T > is an example of Generic Programming, as it can handle lists of various type parameters in the same way. Very useful. Creating a class or method with multiple type parameters surrounded by \ <> like ArrayList \ <T > is called Generic Programming.

Constitution

This article first explains the implementation and usage of the basic GenericClass and GenericMethod. Then, I will introduce how to limit GenericPrograming and how to handle it flexibly. Finally, I will summarize the points to note about GenericProgramming in Java.

Generic Class A simple implementation of GenericClass.

Entry.java


public class Entry<K, V>{ // point 1
  private K key;  // point 2
  private V value;

  public Entry(K key, V value){  // point 2
    this.key=key;
    this.value=value;
  }

  public K key(){return key;} // point 2
  public V value(){return value;}
}
  1. When defining a class, declare multiple type parameters enclosed in \ <> after the class name. K and V are declared in Entry, but K and V have no meaning. Java convention Use the letters T, E, K, V, X, R, U, T1, T2 for the type parameter in.
  2. Type parameters can be used as return types for member variables, constructors, and instance methods.

Client.java


Entry<Integer, String> id = new Entry<String, Integer>(1001, "hitoshi watanabe"); //1
Entry<Integr, String> id2 = new Entry<>(1002, "taro yamada"); //2
var id3 = new Entry<Integer, String>(1003, "hideo kojima"); //3
  1. This is the prototype.
  2. If you declare a type parameter on the left side, the compiler infers the type parameter on the right side. 3.2 The opposite of 2, the writing method in which the compiler infers the left side.

Primitive types cannot be used for type parameters, so boxed Integers are used instead of ints.

Generic Method Type parameters are instance-dependent, so if you want to use type parameters in a static method, you need to declare type parameters that are independent of the instance.

Arrays.java


public class Arrays {
  public static <T> void swap(T[] array, int i, int j){ // point 1
    T tmp = array[i];  //point 2
    array[i]=array[j];
    array[j]=tmp;
  }
}
  1. When declaring GenericMethod, specify the type parameter with \ <> before the return type.
  2. Type parameters can be treated as types in GenericMethod.

Client.java


String[] member = ...;
Arrays.<String>swap(member, 0, 1); //1
Arrays.swap(member, 0, 1); //2
  1. This is the prototype
  2. The compiler infers the swap type parameter from the first argument member.

Generic Programming restrictions

A sufficiently abstract operation like Array.swap could declare a type parameter called \ <T > which does not limit the type. But when you want to do a more restrictive operation, the type parameter is satisfied. You need to set a limit so that only subtypes of the type are included. As an example, we will introduce the implementation when you want to close all the elements by taking ArrayList of the class that implements the AutoClosable interface as an argument.

Sample1.java


public static <T extends AutoClosable> void closeAll(ArrayList<T> elems) throws Exception{ // point 1
  for(T e : elems) e.close(); // point 2
}
  1. You can limit type parameters to Any that implements interface with \ <Any extends interface / class >, or Any that inherits class. Therefore, this Generic Method can only make subtypes of AutoClosable type parameters.
  2. Since it is guaranteed that the type parameter of this GenericMethod implements AutoClosable, the close method provided by AutoClosable can be called.

When \ <T > is declared, the compiler complements \ <T extends Object >. In java, all classes have an Object class in their ancestors, so the methods provided by the Object class can be used.

closeAll method does not have to be GenericMethod

Sample.java


public static void closeAll(AutoClosable[] elems){
  for(AutoClosable e : elems) e.close();
}

##Increased flexibility in Generic Programming
When you want to implement a method that takes an instance with a type parameter as an argument,Instance subtype to take as an argument,It's normal to want to allow supertypes as arguments as well..However,


#### **`BadSample.java`**
```java

public static void printName(ArrayList<Employee> staff){
  for(Employee e : staff) System.out.println(e.getName());
} 

BadSample.ArrayList as an argument like javaWhen,Only Employee type ArrayList can be accepted as an argument.In other words,ArrayList of subclass instances that inherit from Employee cannot be used with this method.That's not enough flexibility as a method, so we use the concept of WildCard.. There are 3 types of WildCard,Explain each.

###SubType WildCard BadSample.In java, I couldn't take a class that inherited Employee as an argument.,SubType Wild Card is used to solve the problem..

Sample2.java


public static void printName(ArrayList<? extends Emplyee> staff){ // point 1
  for(Employee e : staff) System.out.println(e.getName());
}

<? extends hoge>Will accept an instance of hoge's subtype parameter as an argument.hoge subtypes can be treated as hoge in polymorphism.At that time,If the method used is overridden,Overridden method is called.

Recommended Posts

java Generic Programming
java programming basics
Java generic story
Java programming basics practice-array
Java programming (class structure)
All about Java programming
java competitive programming memo
Java Programming Thread Runnable
Amazing Java programming (let's stop)
Java programming (variables and data)
Java Development Basics-Practice ③ Advanced Programming-
Java programming basics practice-for statement
Java
Java programming basics practice-switch statement
Java
[Java] Basic terms in programming
Competitive programming private cheat sheet (Java)
Java Functional Programming Exercise Book --zipWith-
Summary of object-oriented programming using Java
Java learning (0)
Studying Java ―― 3
[Java] array
Java protected
[Java] Annotation
[Java] Module
Java array
Studying Java ―― 9
Java scratch scratch
Java tips, tips
Use OpenCV_Contrib (ArUco) in Java! (Part 2-Programming)
Java methods
Java method
java (constructor)
Java array
java (override)
java (method)
Java Day 2018
Java string
Object-oriented programming
Java static
Java serialization
java beginner 4
JAVA paid
Studying Java ―― 4
Java (set)
[Java] compareTo
Studying Java -5
Newcomer training using the Web-Basic programming using Java-
java reflexes
java (interface)
Java memorandum
☾ Java / Collection
Java array
[Java] Array
Studying Java # 0
Java review
java framework
Java features
[Java] Inheritance
FastScanner Java
Java features