Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using foreach with ArrayList - automatic casting?

ArrayList x=new ArrayList();
x.Add(10);
x.Add("SS");

foreach(string s in x)
{
}

Does it mean that when foreach is run it tries to cast element of array list to type in foreach expression?

like image 220
Lojol Avatar asked Jan 22 '11 11:01

Lojol


People also ask

Can you use forEach with ArrayList?

The forEach() method of ArrayList used to perform the certain operation for each element in ArrayList. This method traverses each element of the Iterable of ArrayList until all elements have been Processed by the method or an exception is raised.

How do you concatenate an ArrayList element in Java?

Approach: ArrayLists can be joined in Java with the help of Collection. addAll() method. This method is called by the destination ArrayList and the other ArrayList is passed as the parameter to this method. This method appends the second ArrayList to the end of the first ArrayList.

Why do we need forEach?

You use foreach whenever :your array is associtive or has gaps, i.e. you cannot reach every element by an incremented number (1,2,5, 'x', -7) you need to iterate in exactly the same order as they appear in the array. (e.g. 2,1,3) you want to be sure not the get into an endless loop.


1 Answers

Yes, if an element is not convertible to the type, you'll get an InvalidCastException. In your case, you cannot cast boxed int to string causing an exception to be thrown.

Essentially, it's equivalent to:

foreach (object __o in list) {
    string s = (string)__o;
    // loop body
}
like image 114
mmx Avatar answered Sep 20 '22 21:09

mmx