Skip to content
Advertisement

When building containers why is using Java Generics better than using the Object Class? (Java Generics & DataStructures)

So I have been reviewing my data structures and came across an interesting thought regarding Java generics and the Object class. I have implemented and run a “generic bag” in two different ways (Notice below: IObjectBag.java, ObjectBag.java, IGenericBag.java, and GenericBag.java) and have used them both (Notice: Below main.java and Output). I have removed some of the unnecessary code as per stack overflow rules but if you want the full implementation, let me know.

Also, I have researched the topic in many websites, books and courses in addition to looking at the source code for the ArrayList class here and I understand that my GenericBag is a better option than my ObjectBag but not well enough to explain it in a practical way during an interview. And I am confused that my GenericBag uses more casting operations than my ObjectBag in its implementation (see Remove and PrintBag).

  1. So, other than the syntactic sugar, why is my GenericBag better? Please use my classes as examples.

  2. Are there any important differences in runtime/overhead/space/time I am not noticing?

  3. How would you answer this question or expect it to be answered in an interview?

Bonus questions: If you want, please answer the bonus questions in the Main and GenericBag comments (I think I can answer them myself though, just want to hear your opinion).

IObjectBag interface:

JavaScript

ObjectBag class:

JavaScript

IGenericBag class:

JavaScript

GenericBag class:

JavaScript

Main class:

JavaScript

Output:

JavaScript

Advertisement

Answer

Problems with your ObjectBag that are ‘automaticaly’ solved by the type safety offered by your GenericBag implementation:

  • Accessing an entry returns Object, at this stage you do not know of what type Object is.
  • You can insert any types of Objects (mixed) e.g a String and an Integer into the same list, this is an anti pattern and causes non readable code (try it with your Generics bag!)
  • Because your compiler knows the type of your GenericBag after you have declared it, at any stage of your code if you hover over your genericBag instance you will know its type, this makes your code more readable and also extendable for other people

Generics also offer way more, imagine you want your GenericBag to only accept numbers, then you could write it as follows:

JavaScript

My suggestion for you is to read some articles on Java basics and especially Generics, having a praxis based way of learning is a good thing, but there are plenty articles that can give you some very nice theoretical insight on the matter.

https://www.baeldung.com/java-generics

Advertisement