Marcus Marcus - 23 days ago 5
Java Question

Typed vs. Non-typed ArrayList

What's the difference between using a typed vs. non-typed

ArrayList
in Java?

For example, Using an
ArrayList
of
CustomObject
:

Typed:

ArrayList<CustomObject> typedArray = new ArrayList<>();
typedArray.add(new CustomObject);


or non-typed:

ArrayList<> nonTypedArray = new ArrayList<>();
nonTypedArray.add(new CustomObject);


Is there any situation where the latter is preferred? Is there any difference when the
ArrayList
is holding different datatypes, e.g. an ArrayList of
String
,
Int
, etc.?

tim tim
Answer

It's never preferable to use the latter option. I don't think that is even possible. I think you meant:

 ArrayList nonTypedArray = new ArrayList();

This syntax is left over from Java 1.4 and earlier. It still compiles for the purposes of backwards compatibility.

Generics was introduced in Java 1.5 which allowed you to specify the types between angled brackets.

It is always preferable to use generics because it is more type-safe.

That is, if you specify

ArrayList<String> typedArray = new ArrayList<String>();

Then you cannot accidentally add an integer to this array list; if you tried to add an integer, the program would not compile.

Of course, Generics ensures type safety at compile time. At runtime ArrayList<String> typedArray = new ArrayList<String>(); becomes ArrayList typedArray = new ArrayList();. This is to maintain backwards compatibility.

Comments