From the course: Advanced Java Programming
Unlock the full course today
Join today to access over 22,600 courses taught by industry experts or purchase this course individually.
Introduction to generics in Java - Java Tutorial
From the course: Advanced Java Programming
Introduction to generics in Java
- [Instructor] Generics are a way to tell a compiler what type of object a collection can contain. Here I have a class called generics example which has two short blocks of code inside the main method. Both blocks do the same thing, they create an array list and add a string to it. Then they get the first element in the list and print it out to the terminal. If I run this program you can see that the output for both is the same. The first example does this without generics. When I assign the string name to the first element in the list, I have to cast it to a string. In the second example, generics are used. When I create the list, I specify in the angled brackets that this is a list of strings. This means that there is no need to cast the object to a string when I assign it to a variable. This might only look like a small change, and the code is actually no shorter. I have just moved the word string but the advantage of using generics means that the compiler checks that only strings…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.