This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help with List class

 
Terry Chambers
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I have an XML file which is stored using an object called "Config". When "Config" is instantiated, it reads the XML file and creates "Server" objects.

In my JSP I want to be able to access some "get" methods associated to the "Server" objects so I have created a Config object and then used a method called "getServers" which creates a List of "servers" to get access to the "Server" objects.



I want to be able to work with those "Server" objects by loading them up in objects in the JSP but the "get" method of "List" returns "Object" types and so the above statement returns an error that I cannot convert from "Object" to "Server". How can I convert/cast this properly so that I can access the "get" methods of my Server objects?

Thanks
Terry
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You just need a typecast like

Server server = (Server) serverlist.get(0);
 
Terry Chambers
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Ok, well, that was way too easy.

Thank you for that.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ofcourse it would have been better when generics would have been used - Config.getServers() should have returned a List<Server> instead of a plain List. Then you wouldn't have needed the type cast.

Type casting should be avoided as much as possible; when you have a type cast in your code, there's something that's not type safe.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic