digression

I have been writing my blog for two weeks. From the beginning, I don’t know how to start, until now, one of my blog posts has been read more than 1000 times and praised by the big guy. On the one hand, I can record my own learning, and also share my knowledge with others. I am actually quite happy, and I hope you will continue to support me as a nine-line code farmer.

The generic

Concept:

Generics, or parameterized types. That is, a type is parameterized from an original concrete type, similar to a variable parameter in a method, in which the type is also defined as a parameter (called a type parameter), and then passed in the concrete type (type argument) when used or called.

use

Let’s start with the generics THAT I used before

package week.third.test;

import java.util.ArrayList;

public class Demo3 {
    public static void main(String[] args) {
        // Create a collection without giving generics
        ArrayList list = new ArrayList();
        list.add("h");
        list.add("a");
        // iterate over the collection
        for (Object obj : list){
            System.out.println(obj);
        }
        // Iterate, printing out the length of each string
        for (Object obj : list) {
            String str = (String) obj;/* Here is the practice of downward transition */
            System.out.println(str.length());
        }
        // Create a collection to give generics
        ArrayList<String> list2 = new ArrayList<>();
        // Add elements
        list2.add("h");
        list2.add("o");
        //list2.add(100); An error is reported at compile time, or if no generics are given
        // Iterate through the collection with the enhanced for
        for(String str2 : list2 ) { System.out.println(str2); }}}Copy the code

A generic class

Define a generic class:public class ClassName<T>{
	private T data;
	public T getData(a) {
	return data;
	}
	public void setData(T data) {
	this.data = data; }}Copy the code

Generic interfaces:

	public interface IntercaceName<T>{
	T getData(a); } When implementing an interface, you can optionally specify a generic type or not, as follows:public class Interface1 implements IntercaceName<String> {
	private String text;
	@Override
	public String getData(a) {
	returntext; }} Do not specify the type:public class Interface1<T> implements IntercaceName<T> {
	private T data;
	@Override
	public T getData(a) {
	returndata; }}Copy the code

Generic methods:

private static<T> T name (T a, T b) {}Copy the code

Generics restrict types

When using generics, you can specify a qualified region for the generics,

For example, it must be a subclass of such and such class or an implementation class of such and such interface in the form of <T extends class or interface 1 & Interface 2>

The role of generics

1. Improve code reuse rate

2. Types in generics are specified at use without casting (type safety, compiler checks type)

Matters needing attention:

The program takes steps to de-generalize after compilation. That is, generics in Java are only valid at compile time. When the result of generics is properly verified during compilation, information about generics is erased, and methods for type checking and casting are added at the boundary between the object entering and leaving the method. That is, generic information does not enter the runtime phase.

Say big things for headlines!

1. What are generics in Java? What are the benefits of using generics?

Generics are a mechanism for parameterizing types. It allows you to write more generic code, such as collections frameworks, by making code applicable to a variety of types. Generics are a compile-time type validation mechanism. It provides compile-time type safety, ensuring that only objects of the correct type can be used on generic types (usually collections of generic types), and avoiding classcastExceptions at runtime.

How do Generics work in Java? What is type erasure?

Generics rely on the compiler compiling the source code by checking the type, erasing the type, and inserting instructions for casts where type parameters appear. The compiler erases all type-specific information at compile time, so there is no type-specific information at run time. For example, a List is represented at run time by a single List type. Why do I erase it? This is to avoid type bloat.

3. What are qualified and unqualified wildcards in generics?

Qualified wildcards restrict types. There are two qualified wildcards, one in which it sets an upper bound on a type by ensuring that it must be a subclass of T, and the other in which it sets a lower bound on a type by ensuring that it must be a superclass of T. A generic type must be initialized with a qualified type, otherwise a compilation error will result. The other hand represents unqualified wildcards because <? > can be substituted with any type.

4.List<? Extends T> and List <? What’s the difference between super T>?

Both List declarations are examples of qualified wildcards, List<? Extends T> accepts any List of type inherited from T, and List<? SuperT > can accept a List of any superclass of T. For example the List <? Extends Number> can take a List or List.

5. How do I write a generic method that accepts generic parameters and returns generic types?

It’s not difficult to write generic methods. You need to replace primitive types with generic types, such as T, E or K,V, which are generally accepted type placeholders.

6. How to write classes with parameters using generics in Java?

This is an extension of the previous interview question. Instead of writing a generic method, the interviewer may ask you to write a type-safe class using generics. The key is still to use generic types instead of primitive types, and to use the standard placeholders used in the JDK.

7. Write a generic program to implement LRU caching?

This is an exercise for anyone who likes Java programming. As a hint, LinkedHashMap can be used to implement a fixed size LRU cache, and when the LRU cache is full, it removes the oldest key/value pairs from the cache. LinkedHashMap provides a method called removeEldestEntry(), which is called by put() and putAll() to remove the oldest key-value pair.

8. Can you pass a List to a method that takes a List argument?

For anyone not familiar with generics, this Java generics topic may seem confusing, because at first glance String is an Object, so List should be used where List is needed, but it isn’t. Doing so will result in a compilation error. If you think about it a little bit further, you’ll see that Java makes sense to do this, because lists can store any type of object including Strings, integers, and so on, whereas lists can only store Strings.

Time to talk:

If the guest officer feel edible appropriate can give a free praise! Thanks, thanks! Go slow, guest officer! I suggest you pack it and come back next time. Shopkeeper QQ: 309021573, welcome harassment!