TubeSum ← Transcribe a video

Java Generics Tutorial

0h 18m video Published Feb 22, 2022 Transcribed Aug 5, 2026 P Programming with Mosh
Beginner 8 min read For: Java developers with basic knowledge of classes and objects who want to understand generics.
AI Trust Score 70/100
⚠️ Average / Some Fluff

"Delivers a solid tutorial on Java generics, though it's part of a course and includes some promotional content."

AI Summary

This video provides a comprehensive introduction to Java generics, explaining the problems they solve and how to use them effectively. It covers creating generic classes, type parameters, bounded type parameters, and the benefits of compile-time type safety.

[00:02]
Introduction to Java Generics

The video aims to teach everything about Java generics, enabling viewers to write Java code with confidence. It is part of the Ultimate Java Mastery course.

[00:46]
Problem: Non-Generic List Class

Creating a list class for integers leads to code duplication when needing lists for other types like users or strings.

[04:05]
Solution Attempt: Object Array

Using an array of Objects allows storing any reference type, but requires explicit casting and can cause runtime ClassCastException.

[07:28]
Generic Class Implementation

Introducing a generic class with type parameter T, allowing reuse for different types and providing compile-time type safety.

[11:56]
Generic Type Arguments and Wrapper Classes

Only reference types can be used as generic type arguments; primitive types require wrapper classes like Integer, with automatic boxing and unboxing.

[14:21]
Bounded Type Parameters

Constraints can be added using 'extends' to restrict type parameters to a specific class or interface, e.g., T extends Number or Comparable.

Generics provide compile-time type safety, reduce code duplication, and eliminate the need for explicit casting, making Java code cleaner and more robust.

Mentioned in this Video

Tutorial Checklist

1 00:46 Create a non-generic list class for integers to see the problem of code duplication.
2 04:05 Attempt to use an Object array to store any type, noting the need for casting and runtime errors.
3 07:28 Create a generic class with type parameter T, using T for fields, method parameters, and return types.
4 11:56 Use reference types as generic type arguments; for primitives, use wrapper classes with boxing/unboxing.
5 14:21 Add bounded type parameters using 'extends' to restrict T to specific classes or interfaces.

Study Flashcards (5)

What is the main benefit of using generics in Java?

easy Click to reveal answer

Generics provide compile-time type safety, eliminating the need for explicit casting and reducing runtime errors.

07:28

What are the two categories of types in Java?

easy Click to reveal answer

Primitive types (numbers, characters, booleans) and reference types (everything else).

04:17

Why can't we use primitive types as generic type arguments?

medium Click to reveal answer

Because generics require reference types; primitives must be wrapped in their corresponding wrapper classes.

11:56

What is the purpose of a bounded type parameter?

medium Click to reveal answer

It restricts the type parameter to a specific class or interface, ensuring only compatible types are used.

14:21

What is the syntax for a bounded type parameter that implements multiple interfaces?

hard Click to reveal answer

Use 'extends' with a single ampersand, e.g., T extends Comparable & Cloneable.

16:46

💡 Key Takeaways

⚖️

Generics Provide Compile-Time Type Safety

This is the core benefit of generics, preventing runtime ClassCastException.

07:28
💡

Object Array Approach is Flawed

Demonstrates why using Object arrays leads to verbose code and runtime errors.

04:05
📊

Wrapper Classes Enable Generics with Primitives

Explains boxing/unboxing, a key concept for using generics with primitive values.

11:56
🔧

Bounded Type Parameters Add Constraints

Shows how to restrict generic types to specific hierarchies, increasing type safety.

14:21

[00:02] everything you need to know about java generics so by the end of this video you'll be able to write java code with confidence hi i'm mash hamadani and i've through this channel and my online school codewoodmash.com this video is

[00:17] part of my ultimate java mastery course so once you finish this video if you want to learn more you may want to look at the complete course now let's jump in at the complete course now let's jump in and get started

[00:34] solve so in this project i'm going to add a new package a new package called generics i'm going to write all the code for this section inside this package

[00:46] now let's say we want to implement a class for storing a list of integers so in this package we add a new class called list

[00:59] field private integer array items private integer array items and we set it to a new int array of 10. now we shouldn't hard code the length of this array here it's better to add a

[01:12] constructor and receive the initial capacity of this array as a parameter but let's not worry about this and instead implement a basic list class so what is the next thing we need here we need a method for adding a new

[01:24] integer to this list so a public method public void add which a public method public void add which gets an integer called item now here we also need a private field for keeping track of the number of items

[01:37] for keeping track of the number of items in this list so private end count now back to our add method we type items of count and we set this to this new item so initially count is zero and we store this item at index zero now

[01:52] here we should increment count so next time we add an item it will be stored at index one okay now we also need a method for getting an integer by its index so public

[02:04] integer get we give it an index and here we return items of index now here we're not validating this index parameter we're not checking to see if it's negative or greater than the number

[02:18] of items in this list let's not worry about these details and focus on an absolute basic implementation of a list so now that we have a list let's go back here we create

[02:30] new list you want to import the one that is declared in this package that we just created because we have another class by the same name in java it's declared in java.util package we don't want that one

[02:43] java.util package we don't want that one so let's import our own class all right now we call the add method and insert an item in this list so

[02:56] first i'm going to add a new class in this package now in this class we could have fields like username password email and so on for now let's not worry about this instead we want to have a list of users

[03:10] this list that we have here we cannot use this class for storing users we can only store integers in this class so with this approach we'll have to create another class

[03:22] called user list user list in this class we're going to have a user array so private user array let's import this type

[03:34] we call it items and set it to new user array of 10. private image account then we'll have to implement our add and get methods that's

[03:47] a lot of code duplication what if in the future we want to have a list of strings so this approach is very tedious and not scalable in the next video i'm going to scalable in the next video i'm going to show you one way to solve this problem

[04:05] one way to solve the problem in the last video is to use an area of objects here because the object class is the base or the parent of all reference types in java remember reference types we talked about them in the first part of this

[04:17] series to refresh your memory we have two categories of types in java primitive types and reference types primitive types are numbers characters and booleans everything else is a reference type so if we use an area of

[04:30] objects here we can store anything in this array for example we can store user objects because the user class extends the object class the object class so here we have an object a

[04:44] here as well the parameter of the atmeter should be an object and also the return type of the get now back to our main class

[04:58] we can store numbers in this array we can also store strings user objects so that's great isn't it not really this

[05:11] reasons but before we talk about these reasons i got a question for you earlier i told you that the object class is the parent of all reference types so we can store any objects in this list however this integer here

[05:25] this is a primitive value it's not an object it's not a reference type so how can we store it here well when we compile this code the java compiler will convert this code to something like this integer dot value of 1.

[05:40] so we have this integer class in java it's a reference type it derives from and this class has a static method valueof which returns a new instance of the integer class so this is the reason why we can pass a primitive value to

[05:54] by the same token we have a wrapper class for every primitive type in java we have float we have double boolean character and so on okay

[06:07] let's rewrite this back what are the problems with this implementation well the first problem is that if you want to get the first item in this list we call the get method now we know that this is an integer so

[06:21] we may hope to store it in an integer variable called number but we have a compilation error because this get method returns an object but we expect that integer so here we have to explicitly cast the result to an integer

[06:35] and this makes our code a little bit verbose and noisy the second problem is that if we use the wrong type here we'll get an invalid cast exception for example let's change zero to one we know that the second item in this list is a

[06:49] string what if we accidentally try to cast it to an integer we run our program a class cast exception now the problem here is that we will not

[07:03] be aware of bugs like this until we run our application and test all the functions so we can only identify these problems at runtime it would be great if we could cache these problems at compile time and

[07:15] that's what generics are for in the next video i will show you how generic video i will show you how generic classes help us solve these problems

[07:28] let's see how generics prevent the problems we discussed earlier problems we discussed earlier so let's add a new class in this package differentiate from the other list implementation

[07:42] now we want this class to be generic so we can reuse it to store different types of objects so right after the name of the class we type these angle brackets and inside these brackets we type a capital t as in short for type or

[07:56] template now we could use any letters here it doesn't have to be a t but t is a common convention another convention is e as in short for element we use that when we want to implement a class that acts

[08:08] as a collection so it can store many elements so here we could use either e or t i'm going to go with t now this t is a type parameter for this class so just like our methods can have parameters our classes can have

[08:22] this t over here represents the type of objects we want to store in this list when we create an instance of this class we'll have to specify an argument or a value for this parameter for example

[08:34] back in our main class let me delete all this code if you want to create an instance or generic list we type new generic list now here we specify the type of objects we want to store in this list for

[08:49] example user or string or integer okay so back to our generic list implementation this t represents the type of objects we want to store here

[09:02] private t array we call it items and set it to new t array of 10. now here we have a compilation error because the java compiler doesn't know the type of t at this stage is it the character

[09:18] class it doesn't know what it is that is why it cannot instantiate it now one simple workaround is to use new object array here and then

[09:30] to t array array okay now just like before we need a field for keeping track of the number of items in this list so private and

[09:42] next we implement our add method so public void add now instead of an public void add now instead of an integer or an object we pass t the type of t will be determined later when we create an instance of this class

[09:56] so we call it item just like before and here we store and here we store item in our array so items of count plus plus equals item finally we need our get method so public

[10:09] t get integer index again instead of an get integer index again instead of an integer or an object we return t okay so here we return items of index

[10:23] now back to our main class when we create a generic list of integer and call the add method look the type of this parameter becomes integer so if i call this method and pass a string i get a compile-time error

[10:39] this is the benefit of generics this generic class ensures that every object now actually let's store this in a variable called list

[10:52] and here we call list dot add now here's the second benefit when we call the get method look we get an

[11:06] integer so if we get the first item we can simply store it in an integer and here we don't need an explicit cast if we had a generic list of users

[11:18] if we had a generic list of users we could add a user object here store it in a user object okay again we don't need an explicit cast

[11:30] so our code becomes cleaner and we get compile time type safety so we can catch our mistakes at compile time rather than at runtime that is the beauty of generics now over the next few videos we're going to study generics in more

[11:44] detail you're going to understand how exactly genetics work under the hood exactly genetics work under the hood so i'll see in the next video

[11:56] when creating an instance of a generic type we can only use a reference type as a generic type argument let me show you what i mean so i'm going to create a generic list of user we can pass the user class as a generic

[12:09] type argument because this class is a reference type we can also use the object class or the string class these are all reference types in java but here we cannot pass the primitive integer type or short or boolean or float these

[12:25] are all primitive types if you want to store these primitive values inside a generic list we have to use their wrapper class so every primitive type in java has a wrapper class let me show you so

[12:38] for the primitive int we have the integer class for the float we have the float class for the boolean we have the boolean class and so on so this boolean class is a reference

[12:50] type that stores a boolean value so if you want to create a generic list of integers we have to write code like this new generic list of integer

[13:02] now let's store this object in a variable of type generic list of integer now look over here this integer is grayed out because it's unnecessary we're duplicating our code so

[13:18] duplicating our code so let's remove that that's better now look at the signature of the add method class but we can pass a primitive integer like one and the java compiler

[13:32] will automatically wrap this value inside an instance of the integer class so it's going to create an instance of the energy class to store this value this process is called boxing so the java compiler is going to put

[13:46] this primitive value inside the box now when we call the get method instance of the integer class so let's get the first item and store it in a primitive int called number

[14:02] now in this case the java compiler is going to extract the value that is stored in that integer object this is called unboxing so this is how we can create generic types that work with primitive values

[14:21] there are times you want to add a constraint or a restriction on a type parameter for example let's say we only want to store numbers in this list some operations that only make sense for

[14:34] numbers to do that here we type extends number now t can only be the number class or any of its child classes but what is this number class well if you search for

[14:47] java number class here you can find the documentation for this class let's look at the documentation for java platform standard edition version 8. so

[14:59] here you can see that the number class is declared in java.lang package and it's the base class for these classes like byte double float integer long and so on so all these wrapper classes around numeric primitive

[15:13] types derive from the number class so with this constraint of string we get a compilation error because this string is not a number so here we can

[15:26] only pass the number class or any class that derives from the number like that derives from the number like integer or float or short this constraint doesn't have to be a class it can also be an interface for

[15:39] example in java we have a popular interface called comparable we use this interface for implementing classes that can be compared with each other for example if we implement this interface in our user class we can compare two

[15:53] user objects based on some criteria like their last login date then we can sort all users based on their last login date we'll look at the section but let's see how applying this constraint works

[16:07] that this list can only store objects that are comparable so back in the main class we can pass short here because short values are comparable we can also pass integer or string but

[16:21] we cannot pass user because our user class does not implement the comparable interface now if we go to our user class and type implement comparable

[16:33] now don't worry about this compilation error we'll come back and fix this later but we're saying that the user class implements the comparable interface you can see that the error is gone in the main method

[16:46] also here we can add multiple interfaces as constraints for example we can type as constraints for example we can type and cloneable this is another popular if you want to be able to clone or copy a class we should implement this

[17:00] interface in that class now we are saying that this generic list can only store objects that are comparable and cloneable and by the way note that here we have a single ampersand so this is

[17:12] we have a single ampersand so this is not the logical and operator okay now back in the main class we cannot pass the user class here anymore because this class only implements the comparable interface

[17:24] we can only pass classes that implement both the comparable and clonable interfaces so this is all about applying constraints now with this constraint we say that we have a bounded type parameter this type

[17:38] parameter this t is bounded it's restricted video as i said this video is part of my ultimate java mastery course that teaches you everything you need to know about java from the basics to more

[17:53] advanced concepts so if you want to learn more i highly encourage you to take a full course it's much faster than jumping from one tutorial to another if you're interested the link is below this video thank you and have a great day

More from Programming with Mosh

View all

⚡ Saved you 0h 18m reading this? Transcribe any YouTube video for free — no signup needed.