What generics are (understand what they are first)

In the process of learning Java foundation, generic absolute is a difficult to understand the knowledge, especially for beginners, and even have a Java programmer, may the understanding of the generic is not so clear, was one of those to see understand, after a long time you forget that, investigate its root, or a lack of understanding for generics. What most people know about generics: “Basic, but vague”

Why generics

The concept of generics was introduced in Java1.5. It wasn’t there before, so why not now? Then you have to think: 1, either the previous technology is too rubbish, need to upgrade 2, or technology development, come out of the new stuff, make Java better 3, or fill the pit, there are parts of the previous, make a pit fill 4,… So, what could this generic be? It’s actually a pothole. Before we say that, let’s look at some code:

This code is a simple set of lists. You may need to note that the List I defined here is not like this:

List<String> stringList = new ArrayList<String>();Copy the code

I don’t know. Can you tell the difference? And this is probably the one that most of us will define when we use it, so those of you who are familiar with generics probably know what this is, but those of you who are not familiar with generics just remember to use it that way. A List is a house in which you can store data. A List is a house in which you can store data. A List is a house in which you can store data, including old people and children.

How about my drawing skills? List is just like a house, in which people and animals can be entered, such as all kinds of cats and dogs

Of course, you can enter data in the List, like strings, integers and so on. This time can produce a problem, what problem MAO, you look, the house can enter inside a variety of species, is the various types of ah, if this house could talk, it said “what thing ah, you what all come to me, what varieties are good, too messy, all remember who is who, you forget it I don’t remember who you are what type, That is to say, for the house, no matter what you come in, I will treat you as “living things”. In my eyes, you are the same type.

Similarly, if you put it in a List, you can put strings, you can put integers in a List, so the List says, I don’t remember which one of you is a string and which one is an integer, I’m going to treat you as an Object class, and why is it an Object class, This is because Object is the parent of all classes, so there is no better way to do it. Whether you are a string or an integer, you must all be Object.

Seemed so perfect, but there is a potential problem, w what problem, you see, we also get a house, for house, inside the house are regarded as “living” type, if I want to find a dog out of the house, then I find out the type is “living”, but I want a puppy, you give me a “beast”, Does not accord with my requirement, how to do?

We all know that there is a casting, ok, I will give you the “beast” forced into a puppy, it doesn’t conform to the requirements, but this problem comes, if you find out is a puppy, you cast it into the dog, that is nothing, but you also could find out the individual, this time you take a man forced into a puppy, No one would like it, would you?

The same is true for a List, you can store everything in it, and it will be treated as an Object, and then if we take a value from a List, we have to cast it, we have to convert Object to the type we want, so if we want a string, If you fetch an integer and cast it to a string, it doesn’t matter. If you fetch an integer and cast it to a string, the integer doesn’t like it, so the program will give you an error.

At first glance, it seems that there is no problem, and the compilation also does not report anything wrong, let’s run it:

ClassCastException cannot convert an Integer to a String. The ClassCastException type is ClassCastException

I just want to store strings in it, but somehow I put an integer in it, because the List doesn’t know what type it is, but it’s all Object. Then we get a ClassCastException when we fetch the data.

I want you to remember what type of data I passed in, so I can’t pass anything else in, so I don’t have to cast it, so I don’t have a ClassCastException.

This you would have thought that the JDK official more can think, as a result, in Java1.5 version will introduce the concept of generic, but a large part of the introduction of generic reason is that in order to solve the problem of our above, ie, I hope I can remember I put into a collection of what type of data, to make a selection, If they are not of the same type, they are not allowed to be stored together. This avoids the ClassCastException error because they are of the same type, so there is no need to cast them.

So now you can see why generics exist. Of course, generics were introduced largely to compensate for a weakness in collections, but they are widely used, not just in Java collections.

Definition and understanding of generics

The above is a detailed introduction to why generics exist and how generics are defined.

Generics are parameterized types, which take the type we are manipulating as a parameter, such as when we create a collection, allowing us to specify the data type of the elements in the collection.

In JDK1.5, we introduced the concept of parameterized types. This is called generics. Generics and parameterized types are the same thing.

Parameterized type

Let’s take a look at the literal meaning, parameterization parameterization, you know, we sometimes watch some fantasy TV show, like someone turns into a beast, you know what that means, he turns into a monster, he transforms, ha ha, so parameterization here probably means become a parameter? So there’s another type, which is a String type, an Integer type, and so on, and so forth, and so forth, and so forth, and so forth, and so forth, and so forth, and so forth, and so forth, and so forth. I don’t know if I’m making myself clear, do you understand? Well, let’s see what generics look like:

List<String> stringList = new ArrayList<String>();Copy the code

This is what we do all the time. This is a generic application. See how it differs from the following:

List stringList = new ArrayList();Copy the code

It is easy to see that there is more than one of this, so how to further understand it?

Understand the generic

Remember we said before, the introduction of generic a large part of the reason is to make the collection element data type to remember him, how to make it remember MAO, implementation is simple, actually is only to a particular type, such as the incoming string type, so long only to string type, such as integer type and other types is not allowed to enter, This ensures that the elements in the collection are of the same type, and the collection remembers them. Let’s look at the house example we gave earlier:

Easy to understand, before the house is open, anyone can enter, now my husband, my this house is used as a dog house, dog nature is only offered to live, the other is not allowed to enter, you a person to let you into you also do not, ah, how make MAO, that is to have a check at the gate device, is just like security, first of all tell security, can only let the dog into, the other is not let into, As a result, every time come over, security check is not the designated type of dog, if not, do not let in, if it is, go in, so this house is all dogs, the name of the dog house ah. The same goes for the set. Now we need to understand how to check the set. Let’s look at the set without using generics:

List stringList = new ArrayList();Copy the code

At this point, it is open, and all types of data can be stored in the List. Now let’s look at generics:

List<String> stringList = new ArrayList<String>();Copy the code

As you can see, there is one more, let’s look at the actual code:

I need a String, you pass in an int, it doesn’t fit, so I can’t store it.

List is a collection, you can deposit to data, to restrict now, not what type of deposit, then the data of the deposit check, how make, that’s at the back of the List add a, become a List, see, this is like those in our examples above the security, responsible for checking incoming data, I’m going to give it a data type, which in this case is String, and then I’m going to check, and I’m not going to store anything that’s not String, so that’s what I’m going to check, where String is the specified data type, that’s generic, that’s parameterized, String is a String, I’m just going to put it there as an argument, and everything that I save into the List is going to be a String. All right? That’s what generics are, taking String as an argument, parameterizing the type, you see, that’s what it is. Such a look and feel generics are well understood, but this is just a basic understanding of the generic generic still have a lot of content, after understanding the basic concepts of the generic type, we also need to look at the other content of the generic type, of course, I must tell you, even if I tell you see above, the following content also may let you understand, look at!

Generic advanced

Diamond grammar

At first glance, this is very advanced, but actually look at the code to know how to work, we have above example of collection generic code:

List<String> stringList = new ArrayList<String>();Copy the code

Is that how you usually write? I guess it says something like this:

List<String> stringList = new ArrayList<>();Copy the code

The difference is that the ArrayList has an Angle bracket and there is a String inside it, which is the type parameter. It was mandatory before Java7, that is, it had to be like this:

List<String> stringList = new ArrayList<String>();Copy the code

But at the beginning of Java7 you could write:

List<String> stringList = new ArrayList<>();Copy the code

In Java7, you can use the type argument to derive the data type of an ArrayList, so you don’t need the type argument, but the <> Angle bracket is required, and the type in the Angle bracket can be derived automatically. Because the <> Angle brackets look like diamonds…

Understand type parameters (key)

Remember what a type parameter is? Look at this line of code:

List<String> stringList = new ArrayList<>();Copy the code

Is the nature of generic parameterized type, that is, the type as a parameter, and the type parameter is the things in the Angle brackets, in this line of code above, the so-called type parameter is the String, this is ok, in addition, we are all in Java methods in the physical parameter and argument, this all know what’s going on, There is a difference between type parameters and type arguments. What is a type parameter and what is a type argument? Do you find it hard to understand? Don’t worry, after my explanation below, you will think it is so simple. This line of code we wrote above:

List<String> stringList = new ArrayList<>();Copy the code

The type parameter String is actually type arguments, which is the actual type parameters, the type parameter is actually the various data types, generic is a parameterized type, type is used as a parameter, so the String is the actual type arguments, a String type,, understand? What is a type parameter? Let’s see how the List interface is defined. Okay?

The List interface in the source code is defined like this, and of course, if you look at the Angle brackets, this is a generic type, but it’s not quite the same as what we saw before, where the Angle brackets were of a specific type, like String, and you put an E there, what the hell is that? First of all, look, remember that Lsit sets can store anything, that is, integers, strings. Now with generics, you can write code like this:

List<String> stringList = new ArrayList<>();Copy the code

So your List here can only store strings, and of course, what if I want the List to store only integers? Is that something like:

List<Integer> list = new ArrayList<>();Copy the code

But in that case, do you see the problem? What about the List in my source code? Requirement is now I actually write code in the List at the back of the generic can be written as a variety of data types, which requires the source of the List definition must be have the general characteristics and then use a to do anything a abstract, is to use some capital English letters in generic as a type parameter, such as E here is a type parameter, In practice, you could write it as String or Interger, so that lists only store certain types of data, and strings are type arguments. Ow, ok, before I learn here are wondering what’s the E, we have seen T, this is what, of these is a generic type parameter, we are creating a specific class, interface or method can convert the type parameter to specific types of parameter, you can have a look at the Map definition, like this:

There’s a K and a V here, so there’s a basic name for all of this, and it goes something like this:

E Element set framework uses K key mapping type V Worth type N number is mainly used to represent the number T Universal type 1 S universal type 1 U universal type 1 V universal type 1

So, what, does it feel like you just opened up here? These are the actual type parameters, such as the Map above, which look like this:

Map<K,V>Copy the code

The actual type argument looks like this:

Map<String,String>Copy the code

Ok!!!! Understanding the parameters and arguments for type parameters, we’ll see what happens next.

The generic use

We introduce on generics, basically is to use a collection class to illustrate, a large part of the reason is that the generic put forward quite a big reason is that in order to make up for the defect of collection, of course I also said, generics are not just limited to the collection, we can customize the generic, such as custom generic interfaces and generic classes and methods.

1. Define generic interfaces

Let’s look at the List definition in the JDK again, which is this:

This is a generic List interface that defines a generic List interface. Let’s define a generic List interface and see how it is defined.

Here we define a generic interface that takes type parameter E and contains a showTypeName method that prints the type name of the actual type argument of the generic. Then we write a class that implements the generic interface:

If you want to create a generic interface for your class, you need to create a generic interface for your class.

Then we implement the method in the generic interface, and get the type name of the type argument passed in. Let’s use this class:

This is a List that we have been using for example. Let’s look at the output:

The parameter type is String. So that’s a very simple example of a generic interface definition. Ok?

2. Custom generic classes

You need to know how a generic interface is defined, and how a class implements a generic interface. Next, I’ll look at how to customize a generic class.

Simple custom here a generic class, to note here, what I said above the door is a type parameter, and introduces several conventional, actually the type parameter here, do you use any capital English letters are ok, as here I’ll use a capital G, then see how to use the generic class:

Let’s look at the output:

How can a generic class be easily customized? Let’s look at how a class can inherit from a generic class.

3. Inherit generic classes

Let’s get straight to the code:

This is a generic class that directly inherits from our implementation. Note that we can no longer inherit a generic class as a type parameter.

That is, when you inherit a generic class, you specify the actual type arguments, and that is when you define the type.

4. Primitive types

We said that when you inherit a generic class, you can no longer follow the form of a generic parameter, but you can get rid of generics completely.

That’s fine, that’s called a primitive type, so what’s the actual output that you use? Let’s use this class:

The type parameter G is used as an Object parameter.

G = G; G = G; G = G;

Because then you can only pass in strings.

There are no generic classes

Let’s use the List in the JDK as an example. First look at the following code:

List<String> stringList = new ArrayList<>();Copy the code

This line of code must be familiar to you, but let’s look at the familiar code:

List stringList = new ArrayList();Copy the code

Through so much interpretation of the above, you must know, that we use the generic form of the following does not, that is to say what is itself a List can be stored, but now add generics, can only store specific data types, such as the List here, which is from the List into a List, but in fact, It’s not generating a new List, it’s essentially a List, except that the List can only load strings, but the List is still the same List, so ArrayList is not a new class to implement, But you can view it as a subclass of ArrayList. So, generic classes, in fact, don’t exist.

The wildcard

There is also the concept of wildcards in generics. How do you understand this? Let’s look at the code:

If there is such a method, it is not special, if the argument in the method is a List, why special, because List is a generic interface.

But our List doesn’t specify the actual type argument, and that can cause some problems, it can cause generics warning problems, so it’s better to specify the actual type parameter, but there’s also a problem here, which is that I’m not sure what the actual type argument of the List is going to be, That is, it is possible to pass in a List like this:

List<String> stringList = new ArrayList<>();Copy the code

It is also possible to pass in a List like this:

List<String> integerList = new ArrayList<>();Copy the code

How do you specify it? Do this:

That sounds right. Let’s try:

Unfortunately, there is an error here, but it can be summed up in one sentence:

String is a subclass of Object, but List is not a subclass of List

Remember this, know here certainly is not, that how to do? Here’s where the wildcard comes in, and that’s it:

We can use the Test method to pass in a List like this:

List<String> stringList = new ArrayList<>();Copy the code

You can also pass in a List like this:

So, if you use wildcards, you can pass in more types, but sometimes you don’t need to pass in all of them. Hopefully, there are some limitations, and then you need to set the upper and lower limits for wildcards. I won’t expand on this for space.

Generic method

Generics are a bit of a chore to understand. As it turns out, the generic approach is a little hard to understand. What is a generic method? In a nutshell, a generic method is:

When declaring a method, you can define one or more generic parameters

Here’s a comparison with generic classes. For generic classes, such as this one:

When we instantiate this class, we need to specify the specific type argument, such as String or Intenger, so for generic methods, it is defined as a generic parameter, and the actual call needs to specify the generic argument (i.e. the specific type of the generic).

Define and use generic methods

Next we’ll look at how to define generics. First we’ll look at a normal method definition:

This is a normal method definition, but the logic seems to be abnormal. Why? This is not necessary. We need to pass in the name of the parameter as String, and we want to print the name of the parameter as if you would only believe it if we gave it to you. So let’s see how to define a generic method. You know, how do we define a class, is there a keyword class, how do we define an interface? Is it the interface keyword, so defining these special things, there has to be a special thing, so how do you define generic methods? You see:

This is a simple definition of a generic method, and the important thing to note here is, how can you say that you are defining a generic method? Here is a symbol of the red box of generic, that is to say, you want to define a generic method, so you have to access modifier (public) here and return values between write, this is a generic logo, on behalf of you this is a generic method, by the way, the T here is a generic parameter, also can be other capitals, We talked about this before, so you’re looking at this generic method, let’s say we call this generic method:

Okay, so we’re passing in a generic method, so we can pass in different types, so we can see what the type is, and notice that when we write a generic method, we pass in certain types, but when we use generics, we can pass in various types, Then you can test some type names that you don’t know what type they are. So, the syntax of a generic method definition is as follows:

The modifier < T, E,… > Return value type Method name (parameter list) {method body…… }

Let’s contrast this with the generic methods we defined:

The public modifier is the list of generic parameters, which can contain multiple generic parameter names, i.e., those uppercase letters, followed by void, which is the return value type, and then the method name and parameter list.

The key summary

Let’s look at the definition of the generic method:

Here are a few points to highlight: 1, access modifiers, and among the return value of this generic list, which is very important, is pretty and a sign of generic method, with this you can called generic method 2, representative will use the generic type T, only this time, you may only be used in the method the generic type T3, otherwise, you need to know is this T is generic parameter named, It could be T,E,K, whatever, just capital English letters

Learning advice for generic methods

For the generic Java based on this, I’ve always thought is an important knowledge point, of course, this is the case, so the need to understand thoroughly the knowledge points, but another reality is that the understanding of the generic type or a certain threshold, especially for beginners, the generic methods in the generic and may be a little bit hard to understand, So for this piece of learning, it is not recommended to buckle at the beginning, have a basic understanding, such as the above I introduced the basic knowledge of generic methods, just start to understand these, of course, generic methods are not only these, but we will not study in depth. It’s a step-by-step process, and a separate article will cover generics in more detail.

Generic erase and transform

What is this generic erasure? In general, if you ask about generics in an interview, there is a high probability that you will be asked about the removal of generics. Let’s take a look at this code:

Guess, are these two arrayLists of the same type? Take a look at the results:

As you can see, the two are exactly the same, which means that the generic arguments String and Integer don’t have any intrinsic effect on the ArrayList. It’s actually pretty straightforward:

Generic here is equivalent to a security check, specifies a specific data type, want to had to pass through the generic logging data in the collection of the security check, and specify the data type is not the same, are not allowed to store, this is to ensure the storage type is the specified type, that is to say, I just wanted to store the set uniform data types, w how to do, Then make an inspection device (generic), have the effect of a filter data, but you check this device only play the role of a check filter, does not affect my itself, for example is like I want to open a conference for programmers, chose a hotel, the hotel is only allow programmers to enter, so find a security guard (generic) stood at the door, Only allow programmers to enter, not programmers don’t let into, so before the start of the conference (compilation phase), guards at the door, the door only to programmers, wait staff are present, then certainly are programmers in the hotel, so the security tasks at this time is over, and then the security guard can withdraw the (generic erasure), And then we start the meeting (run phase)

So that’s generic erasure, okay? Am I making myself clear? In other words, generics are checked at compile time. At compile time, data that does not conform to the specified type will be checked for errors, such as the following code:

ArrayList<String> stringArrayList = new ArrayList<>();Copy the code

Because you specify the specific generic argument String, you can only add strings here. The compile phase checks that if you add something other than a String, it will report an error.

So once you’re done, this ArrayList is going to be all strings, and when you run it, all the generic information gets wiped out, so there’s nothing generic about it, so the ArrayList itself can store everything, but now I’m adding a generic to make sure that I store everything of the same type. Another example is that there is a thatched house, originally the thatched house who can go in, but now rules (generic), worth a $to get in, but even in are worth a $, the thatched cottage is the original thatched house, it is not likely to become the luxurious villa (just for example, refused to bar fine) in addition to erase, There is also a transformation, which is easy to see as an example, by looking at the code:

This is a simple generic class we defined earlier. Now we use this class:

We specify that the specific generic argument is a String, so when the code is actually compiled, the G is replaced with a String, which looks something like this:

This is a type conversion. In simple terms, the generic parameters you define are replaced at compile time with the actual generic parameters you specify.

conclusion

Actually I have been think generic this thing is a bit like security, is the gatekeeper, in accordance with the provisions of you, who is allowed to can go to, who can not go, of course, can not into is stored here questions, such as collection, whether can you add data to it, this is after you to the rules and the rules you can make a variety of, Is flexible, actually about generic, are just beginning to understand the hurdles, understand the feel fully, but understanding will not necessarily be mastered, behind some source code, the use of generics are many, but you still don’t understand, but on the premise of understanding, you may read the source code, learning is such, need to constantly iteration, repeatedly polished, Can’t stop!

Recently, I have sorted out Java architecture documents and study notes files, architecture videos and HD architecture advanced learning maps to share with everyone for free (including Dubbo, Redis, Netty, ZooKeeper, Spring Cloud, distributed, high concurrency and other architecture technical information). I hope it can help you review before the interview and find a good job, but also save you time to study in the online search materials, you can also pay attention to me and there will be more dry goods to share.