---
title: 'Java Generics Tutorial'
source: 'https://youtube.com/watch?v=7i3Rliqzquw'
video_id: '7i3Rliqzquw'
date: 2026-08-05
duration_sec: 1092
---

# Java Generics Tutorial

> Source: [Java Generics Tutorial](https://youtube.com/watch?v=7i3Rliqzquw)

## 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.

### Key Points

- **Introduction to Java Generics** [00:02] — 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.
- **Problem: Non-Generic List Class** [00:46] — Creating a list class for integers leads to code duplication when needing lists for other types like users or strings.
- **Solution Attempt: Object Array** [04:05] — Using an array of Objects allows storing any reference type, but requires explicit casting and can cause runtime ClassCastException.
- **Generic Class Implementation** [07:28] — Introducing a generic class with type parameter T, allowing reuse for different types and providing compile-time type safety.
- **Generic Type Arguments and Wrapper Classes** [11:56] — Only reference types can be used as generic type arguments; primitive types require wrapper classes like Integer, with automatic boxing and unboxing.
- **Bounded Type Parameters** [14:21] — Constraints can be added using 'extends' to restrict type parameters to a specific class or interface, e.g., T extends Number or Comparable.

### Conclusion

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

## Transcript

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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
we can store numbers in this array we can also store strings user objects so that's great isn't it not really this
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
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.
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
this is the benefit of generics this generic class ensures that every object now actually let's store this in a variable called list
and here we call list dot add now here's the second benefit when we call the get method look we get an
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
