Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Arraylist is typesafe or strongly typed?

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.?

like image 716
Red Swan Avatar asked Aug 01 '13 02:08

Red Swan


People also ask

Is ArrayList strongly typed C#?

ArrayList belongs to System. Insertion and deletion operation in ArrayList is slower than an Array. Arrays are strongly typed which means it can store only specific type of items or elements. ArrayList are not strongly typed.

Can ArrayList be any type?

Since ArrayList supports generics, you can create an ArrayList of any type. It can be of simple types like Integer , String , Double or complex types like an ArrayList of ArrayLists, or an ArrayList of HashMaps or an ArrayList of any user defined objects.

Is ArrayList generic in C#?

C# ArrayList is a non-generic collection. The ArrayList class represents an array list and it can contain elements of any data types. The ArrayList class is defined in the System.

Is type-safe the same as strongly typed?

"Type Safe" means that there's no casting involved and no run-time type errors can occur. Some people argue that "Strongly Typed" mean nothing, or "it's good", or "i'm comfortable with it". Anyway, "Type Safe" relates to a portion of code or API, when "Strongly Typed" refers to a whole language or platform.


2 Answers

An ArrayList is not typesafe. What this means is that ArrayList can be assigned a value of any type:

ArrayList myList = new ArrayList();
myList.Add("this is a string");
myList.Add(19); //Notice that this is an int, but it doesn't throw an error!

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 as List<T>

like image 69
Dave Zych Avatar answered Oct 05 '22 13:10

Dave Zych


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.

like image 32
Joel Coehoorn Avatar answered Oct 05 '22 14:10

Joel Coehoorn