"Another cool topic."
"The surprises just keep coming! Is it my birthday?"
"Today, I'll tell you about generics. Generics are types that have a parameter. In Java, container classes let you indicate the type of their inner objects."
"When we declare a generic variable, we indicate two types instead of one: the variable type and the type of the data it stores."
"ArrayList is a good example. When we create a new ArrayList object, it's convenient to indicate the type of the values that will be stored inside this list."
Code | Explanation |
---|---|
|
Create an ArrayList variable called list .Assign an ArrayList object to it. This list can only store String objects. |
|
Create an ArrayList variable called list .Assign an ArrayList object to it. This list can store any values. |
|
Create an ArrayList variable called list .Assign an ArrayList object to it. This list can only store Integer and int values. |
"Sounds super interesting. Especially the part about storing values of any type."
"It only seems like that's a good thing. In reality, if we put strings into an ArrayList in one method and then expect it to contain numbers in another method, the program will crash (terminate with an error)."
"I see."
"For now, we won't create our own classes with type parameters. We'll just use the existing ones."
"Can any class be a type parameter, even one that I write?"
"Yes. Any type except for primitive types. All type parameters must inherit from the Object class."
"You mean I can't write ArrayList<int>?"
"Indeed, you can't. But Java developers have written wrapper classes for each of the primitive types. These classes inherit Object. This is how it looks:"
Primitive type | Class | List |
---|---|---|
int | Integer | ArrayList<Integer> |
double | Double | ArrayList<Double> |
boolean | Boolean | ArrayList<Boolean> |
char | Character | ArrayList<Character> |
byte | Byte | ArrayList<Byte> |
"You can easily assign primitive classes and their analogs (wrapper classes) to each other:"
Examples |
---|
|
|
|
|
|
"Great. I think I'll try to use ArrayList more often."
GO TO FULL VERSION