Object casting
I need clarification on this casting statement inside the loop, so I can get a better understanding of Object casting:
recordList =new ArrayList();
......
for(int i;....){
((DTO)recordList.get(i)).getName()
}
This translates as DTO (name of destination class) casting the recordList object reference where it allows me to take a value of DTO type and "cast" it to another type, in the sense of molding or reforming the recordList object?
Which in this case the DTO type is casting the recordList.get(i) object to a DTO type which uses the DTO getName() method to fetch the value?
# 1
<%
ArrayList appDataProfile = (ArrayList)session.getAttribute("applications");
for(int j = 0; j < appDataProfile.size(); j++)
{
ApplicationTO appTO = (ApplicationTO)appDataProfile.get(j);
String app = null;
if (appTO.getAppName() != null) {
app = appTO.getAppName();
}
%>
<tr>
<td>
<%= app == null ? "" : app.trim() %>
</td>
</tr>
<% } %>
skp71a at 2007-7-29 18:03:07 >

# 2
"Casting" an object doesn't change it in any way shape or form.
It just lets you refer to it with a more specific subclass than you were before.
list.get(i) returns an Object.
Object does not declare that it supports the getName() method.
Therefore you need to cast the item from the list into something which does.
The item in the list always WAS of type DTO (or a subclass of that type) but doing a cast lets you refer to it as such in your java code.
It probably becomes easier to understand if you break it into individual steps.
// retrieve object
Object obj = recordList.get(i);
// cast to DTO
DTO dto = (DTO)obj;
// get name from DTO
String name = dto.getName();
# 3
I would add, if you're using Java 1.5 or newer, then apply generics on the ArrayList, so that you don't need to cast the thing.
recordList = new ArrayList<DTO>();
for(DTO dto : recordList){
String name = dto.getName();
}