Java Hashtable problem

i am trying to create a hashtable but continually get a oncompatability type error

here is the class that I wrote

public class PageHash {

// HashMap of Pages

private Hashtable pageHash;

public PageHash(){

// Create the a Hash to hold all the pages

pageHash = new Hashtable();

// Add Pages

pageHash.put("testPage", new Page("testPage","/test.jsp"));

}

public Page getPage(String pageName){

return pageHash.get(pageName);

}

}

Here is the error

PageHash.java:20: incompatible types

found: java.lang.Object

required: com.project.Page

return pageHash.get(pageName);

^

What really confuses me is that I found an example that compiled just fine and when I trie to do the same thing they did it comes up with the same error.

The code that I compiled does this...

Enumeration enum = hash.keys();

Object obj;

while (enum.hasMoreElements()) {

obj = enum.nextElement();

System.out.println (

obj + ": " + hash.get(obj));

}

When i try something similar it comes up with the same error. Any insite or help on this subject would be VERY much appriciated

[1254 byte] By [jondwainhartzler] at [2007-9-26 2:09:15]
# 1
You need to explicitly cast it before returning it..return (com.project.Page)pageHash.get(pageName);
pbalaram at 2007-6-29 8:58:44 > top of Java-index,Archived Forums,Java Programming...
# 2

hi,

the problem with you is the following: the method "public Page getPage(String)" returns an object of class com.project.Page and not of class java.lang.Object. However, that is exactely what you return, because the method call "Hashtable.get(Object)" returns an object of class java.lang.Object. So you have to cast the returned value into a Page object:

public Page getPage(String pageName){

return (Page)pageHash.get(pageName);

}

However, I do not really understand what you meant by the last part and where the error should be.

best regards, Michael

Michael_Rudolf at 2007-6-29 8:58:44 > top of Java-index,Archived Forums,Java Programming...
# 3

> When i try something similar it comes up with the

> same error. Any insite or help on this subject would be

> VERY much appriciated

I suspect that what you did wasn't really that much similar...

System.out.println(obj + ": " + hash.get(obj));

this doesn't give you any errors because the toString() method (it is called to convert the objects to Strings) is defined in java.lang.Object. But some other methods like eg. eatAnApple are not so obj.eatAnApple() is illegal.

If you know that the runtime class (say, AppleEater) of an Object defines the method eatAnApple you can call that method by casting the object to AppleEater: ((AppleEater) obj).eatAnApple() is legal.

jsalonen at 2007-6-29 8:58:44 > top of Java-index,Archived Forums,Java Programming...