I don't know what exactly the difference between "Strongly typed" and "Type safety" is!
Could you please clarify this in a simple language?
Suppose we are using Arraylist, but I am unable to conclude it is typesafe or strongly typed. or can we use it as both.?
The
ArrayList
data structure is a not type-safe, nor strongly-typed. You cannot guarantee what type of object is in anArrayList
, thus everything is stored as anObject
, similar to how objects are stored inSession
cache for ASP.NET.The biggest downside to using
ArrayList
was the casting that needed to happen whenever you wanted to get access to the objects in the actual list. If any of the values in the list were not of the type you were expecting, then you would potentially get casting exceptions and the code to deal with that was just ugly.Use generics wherever possible, with
List<T>
being the closest generic type to theArrayList
data structure.An
ArrayList
is not typesafe. What this means is thatArrayList
can be assigned a value of any type:This is an issue because when you go to use the list, you don't know the types that are in the list. The chances of having an error thrown are very high.
Avoid using
ArrayLists
! Use a generic list instead, such asList<T>
I'm not sure I understand your question.
"Strong/weak typed" is a quality of programming languages. Java is strongly typed, which means it has a strict syntax, and it can find problems in your code at compile time, before errors make it to run time.
Java may not exactly be type safe, though (I'm not sure of the exact answer). It allows generics, which means you can make an ArrayList of Strings (
ArrayList<String>
), ArrayList of Integers (ArrayList<Integer>
), ArrayList of Booleans (ArrayList<Boolean>
).ArrayList<T>
means you can substitute<T>
with any object.ArrayList<? extends T>
means you can substitute with any A, B, C, Potato, etc. that extends T.Say you have the following classes:
You can even have an ArrayList of any child of a User object, for example:
ArrayList<User>
. To this list, you can add Student, Admin, and Teacher objects.But if you do not specify what type of data this ArrayList holds (eg:
List l = new ArrayList();
), you can place any Object in it, causing it to not be type safe.An example of generics abuse can be seen on Wikipedia.
Type-safe and strongly-typed are loaded phrases, such that it's hard to get programmers everywhere to pin down a precise definition. But there is at least enough consensus to state that ArrayLists are neither in every way that matters.
Do not use ArrayLists! Instead, use the generic
List<T>
collection.