Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-generic collections in Java - any uses?

Are there any situations where it's better to use a non-generic collection in Java rather then generic (or they still exist only for backward-compatibility)?

like image 562
alex440 Avatar asked Dec 05 '12 00:12

alex440


People also ask

What is non-generic in Java?

The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes the code stable by detecting the bugs at compile time. Before generics, we can store any type of objects in the collection, i.e., non-generic. Now generics force the java programmer to store a specific type of objects.

What is a non-generic collection?

A Non-generic collection is a specialized class for data storage and retrieval that provides support for stacks, queues, lists and hash tables. Namespace. The Generic Collection classes are in the System. Collections. Generics namespace.

Why do we need generic collections?

Using generic collections gives you the automatic benefit of type safety without having to derive from a base collection type and implement type-specific members.

When would you not use generics in Java?

Limitation of generics Firstly, primitive types (like int , long , byte , …) are not allowed to be used in generics. It means whenever you need to parameterize your generic type with a primitive one, the respective class wrapper ( Integer , Long , Byte , …) has to be used instead.


1 Answers

Absolutely not. In the case in which you can't infer types at declaration time, use a ? as a type specifier - that's what it is for. (There are cases where using ? would restrict you from invoking certain methods, such as List.add(). In such cases, you can find a more restrictive type specifier; Object usually works).

The non-generic usage is still supported because, technically, there is nothing wrong in not using it; you're just going to end up writing more casting instructions and put yourself in a higher risk for ClassCastException's, but it is technically legitimate as far as the specification is concerned.

Overall, there is no case (that I can think of) where avoiding generics is "better than" using them. At the worst case (when you must use ? or Object at declaration time), both approaches are equal.

like image 164
Isaac Avatar answered Oct 04 '22 17:10

Isaac