Below is the sample code :
for(int i = 0; i < clientListFromFile.size(); i++)
{
DisplayClient dc = null; // DisplayClient is another class
dc = (DisplayClient)clientListFromFile.get(i); // clientListFromFile is the a list.
}
can I know what is the means of putting a Displayclient infront the clientListFromFile ?
int prevID = (int)clientList.get(clientListCount-1);
this is another example. why put the (int) infront clientList.get(clientListCount-1) ?
It’s a cast – you’re telling Java that the variable is of a type that might be more specific than it knows about at compile time. With this comes a degree of danger, in that you have to check at runtime it’s definitely of that type, otherwise an exception will be thrown.
This used to be used extensively, especially in collections, before the introduction of generics. However, generics provide a greater degree of defining types at compile time, so many casts are no longer needed. If you find you need casts when retrieving items from the list, you’re probably not declaring the generic type properly (or at all), and should look into fixing this.
The following code uses the old syntax, without generics. Note how the last line doesn’t compile, because the compiler doesn’t know anything about the type of the list, so the type is always object. Hence, we need a cast to get it to work.
This approach is discouraged now, and really is only still allowed for backwards compatibility reasons (it was the only way of doing things before generics were introduced.) We have to remember the type of the list, what was put in it and cast accordingly – and if something that’s not a string makes its way into the list, nothing would stop it. The following example uses generics so does away with the cast:
With this approach, everything we put into the list and get out of the list is guaranteed to be a string – anything else and the code won’t compile.