Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Generics in Java Generics in Java A Generic Solution

Why is it that you no longer need to cast milk/oranges when using Generics?

I don't fully comprehend how using generics allows the instances of box to use milk and oranges respective functions.

1 Answer

Because of what happens when the Box class is called. When you add the "<>" in the Class declaration you're saying that you're passing in "Types" and not values: values can be anything while types are explicitly what you say they are.

Thus when declaring "Box<Milk>" the code states that this Box only has the Milk type.

Accordingly when declaring "boxOfMilk.add(oranges)" the IDE cross-checks the Box type that was declared above, which should be MIlk, and says this will create a compilation error. Why? Because "boxOfMilk" was made with the explicit Type "Milk" and only expects to receive the Milk type. Trying to use the add method to add "oranges" violates this explicitly, so the IDE can detect it, and warn us to fix it.

In other words...

Generics not only makes for cleaner & easier-to-read code, but Generics also let us set safeguards against our own mistakes when coding that an IDE can help detect. Even if you do not have an IDE to help you the process of using Generics makes these mistakes easier to spot since casting - and all of those parentheses - can be difficult to read and properly parse for a human.