jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes Help with List class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Help with List class" Watch "Help with List class" New topic

Help with List class

Terry Chambers

Joined: May 11, 2009
Posts: 17

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?

Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

You just need a typecast like

Server server = (Server) serverlist.get(0);

[Jess in Action][AskingGoodQuestions]
Terry Chambers

Joined: May 11, 2009
Posts: 17

Ok, well, that was way too easy.

Thank you for that.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15081

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.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link: http://aspose.com/file-tools
subject: Help with List class
It's not a secret anymore!