• Post Reply Bookmark Topic Watch Topic
  • New Topic

Object typecasting  RSS feed

 
Vishal Arora
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given below is a jsp code that i found in a book and i copied it as it is:
<%@page import="java.util.*"%>

<html>

<body>
<h1 align = "center">Beer Recommendations JSP</h1>
<p>
<%
List styles = (List)request.getAttribute("somestyle");
Iterator it =styles.iterator();
while (it.hasNext()){
out.print("<br>try:" + it.next());
}
%>


</body>
</html>
Now my question is that how can we typecast a ServletRequest object to a List object. If it would have been
List styles = (List)(request.getAttribute("somestyle"));
then it would been a correct one since the return type of getAttribute() method is of type Object.
Please help me out in this as i am a bit confused.
Thanx
Vishal
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'll help you out by moving your post to our Servlets forum
[ September 22, 2005: Message edited by: Barry Gaunt ]
 
Daniel Rhoades
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use this form when you want to do an operation on the result of a cast:

( (List) request.getAttribute("somestyle") ).get(0);

Use this form when you simply want to cast the attribute and save it as an object (which you can then do operations on)

List list = (List) request.getAttribute("somestyle");
list.get(0);

The latter form is perferable...
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66306
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not really a servlet question, per se.

Your two examples:



are functionally equivalent.
 
Gregg Bolinger
Ranch Hand
Posts: 15304
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to Java In General (Intermediate)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!