CodeGym /Courses /New Java Syntax /What are generics?

What are generics?

New Java Syntax
Level 13 , Lesson 3
Available

"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
ArrayList<String> list = new ArrayList<String>();
Create an ArrayList variable called list.
Assign an ArrayList object to it.
This list can only store String objects.
ArrayList list = new ArrayList();
Create an ArrayList variable called list.
Assign an ArrayList object to it. This list can store any values.
ArrayList<Integer> list = new ArrayList<Integer>();
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&ltint>?"

"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
int a = 5;
Integer b = a;
int c = b;

Character c = 'c';  //the literal c is a char
char d = c;
Byte b = (byte) 77;  // The literal 77 is an int
Boolean isOk = true;  // the literal true is a boolean
Double d = 1.0d;  // The literal 1.0d is a double

"Great. I think I'll try to use ArrayList more often."

Comments (27)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Fadhil Radhian Level 18, Semarang, Indonesia
25 March 2023
Generic also present in Typescript
Anonymous #10782038 Level 24, United States of America
18 March 2024
How is it at accenture? I got an offer from them but I have heard bad things.
Stephen Haokip Level 8, imphal, India
18 June 2020
i progressing thru the lesson is because i have some java knowledge before. this app gives u work n then teaches you. which makes it beginners unfriendly.
Mihai Bone Level 8, Bucharest, Romania
20 October 2020
They do it on purpose to make you research on google for solutions, is a feature not a bug :D
Clint Level 22, cincinnati, united states
18 November 2020
no other book or course does it this backwards
Hoist Level 4, San Diego, United States
20 February 2024
many paying $ for receiving the Pain of researching unfamiliar topics ;
Gellert Varga Level 23, Szekesfehervar, Hungary
26 April 2020
"if we put strings into an ArrayList in one method and then expect it to contain numbers in another method, the program will crash." Notice: 1.) I don't got a program-crash (with JDK8) if i wrote this:

ArrayList mixedList = new ArrayList();
	mixedList.add(cat1);
	mixedList.add("Blah-blah");
	mixedList.add(1);
The program worked flawlessly. However, the output added a comment: "Notice: .... unsafe operation." 2.) With JDK8, when i did the declaration of the mixed list this way:

ArrayList<Object> mixedList = new ArrayList<>();
	mixedList.add(cat1);
	mixedList.add("Blah-blah");
	mixedList.add(1);
	
	for (Object obj : mixedList)
	    System.out.println(obj);
The program worked flawlessly. And the output didn't add any comment! 3.) With JDK-11, when i wrote this without any diamond operator:

ArrayList mixedList = new ArrayList();
the program worked well even then, and the output didn't add any comment.
AfEi Level 19
12 May 2022
crash:

public static void main(String[] args) {
        ArrayList list = new ArrayList();
        list.add(123);
        list.add("abc");
        System.out.println(totals(list));
    }
    public static int totals(ArrayList list) {
        int sum = 0;
        for (int i = 0; i < list.size(); i++) {
            sum += (int)list.get(i);
        }
        return sum;
    }
Gellert Varga Level 23, Szekesfehervar, Hungary
18 May 2022
Yes, I probably didn't interpret that sentence well. (Unfortunately, I don't have a high level of English.) Your example code clearly shows in which case the program will crash. I would modify the quoted sentence in the lesson in this way, in this form I would have understood it better already at first reading: "if we put strings into an ArrayList in one method and then another method want to work with this list as if it contains numbers, the program will crash."
Krzysztof Kosała Level 21, Wejherowo, Poland
19 November 2023
It's not crushed because cat1, "Blah-blah" and 1 - everything of this extends Object class. And object class has default toString() method. So if you only want to display it, it's ok but in another more complicated operation will throw exception.
2 January 2020
:P
31 July 2019
A good additional reading on ArrayLists and Wrapper Classes is at Javanotes 8.1 (textbook online).
Joe M Level 47, Owings Mills, United States
20 November 2020
That is a good book!
Finn Level 11
20 May 2019
Hey, what would happen if i do this?

ArrayList<String> myList = new ArrayList<>();
Would myList reference a ArrayList that can just store Strings or any Value?
Berkson Level 17, Fortaleza, Brazil
22 May 2019
Only store Strings because you declared the diamond operator <String> . If you declare :

ArrayList list = new ArrayList();
You can store any value. Ex:

list.add(23);
list.add("teste");
Will work without a problem. You can iterate over the list with a Iterator without declare the diamond operator too, but if you use, for example, the first value on a method that uses a string as argument you'll must do a downcast to string, cause when you add something to a list of this type, without diamond operator specifying the type "<String>", we add to the list Objects. The ArrayList list receives objects.
Henk Level 19, Pretoria, South-Africa
25 April 2019
what on earth are you talking about in the above section ? sheesh.... How about explaining in "English" what the reason is you have int a = 5 or Integer a = 5 ? I guess this section I'll have to read up on seperately from this course, I don't get the lingo.
Alex Vypirailenko Level 41, USA
25 April 2019
Each primitive type has a "wrapper" class designed for it, which is written with a capital first letter, just like any other class. As an example, we can assign number 5 to both "int a" and to "Integer b", but you can do a lot more with the variable b, because the Integer class has a few methods (you can see them here) which can be used to manipulate the data. However, by using a wrapper class you will be using a lot more memory and is not an efficient use of resources, unless there's a real need for this in the project/program you are writing the code for. More information on the wrapper classes can be found here.
Henk Level 19, Pretoria, South-Africa
27 April 2019
Thank you Alex, for taking the time to answer my question, it makes sense :)
Ivaylo Trifonov Level 25, Madrid, Spain
14 March 2019
https://docs.oracle.com/javase/tutorial/java/generics/index.html Other good article about Generics.
// Java Poser Level 18, Cincinnati, United States
24 February 2019
My power level is rising immediately!!
Hashirama Level 26, Port-Harcourt, Nigeria
17 January 2019
Is it okay to say generics is just like composition: having a type in a type with the difference being that this inner type can be of any type?