The Artima Developer Community
Sponsored Link

Java Answers Forum
generic method unchecked cast problem

2 replies on 1 page. Most recent reply: Aug 28, 2008 10:35 AM by A Basu

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
A Basu

Posts: 2
Nickname: altamit
Registered: Aug, 2008

generic method unchecked cast problem Posted: Aug 27, 2008 7:07 PM
Reply to this message Reply
Advertisement
class Base // a base class for all my objects
{
}

class Cache // holds objects of various subclasses of Base
{

private Map<String, Base> objTable = new Hashtable<String, Base>(INITIAL_ENTRI
ES);

public <T extends Base> List<T> getObjectsByType(String typeName) {
List<T> objs = new ArrayList<T>();
synchronized (objTable) {
Iterator<Base> itr = objTable.values().iterator();
Base obj;
while (itr.hasNext()) {
obj = itr.next();
if (obj.isObjectOf(typeName)) { // isObjectOf() is available already
objs.add((T)obj); // UNCHECKED CAST: Base to T
}
}
}
return objs;
}

}

CALLING CLASS SNIPPET:

List<Derived1> class1Objs = singletonCache.<Derived1>getObjectsByType("derived1");

You dont really need the <Derived1> before the word getObjectsByType above, since the compiler figures out the return type from the left side of =.

My PROBLEM: how to get rid of the UNCHECKED CAST shown above.


Vincent O'Sullivan

Posts: 724
Nickname: vincent
Registered: Nov, 2002

Re: generic method unchecked cast problem Posted: Aug 28, 2008 1:48 AM
Reply to this message Reply
The simplest solution would probably be to add the annotation
@SuppressWarnings("unchecked")
immediately before the method declaration.

V.

A Basu

Posts: 2
Nickname: altamit
Registered: Aug, 2008

Re: generic method unchecked cast problem Posted: Aug 28, 2008 10:35 AM
Reply to this message Reply
that would be the last resort.

Flat View: This topic has 2 replies on 1 page
Topic: Run a java class within another class Previous Topic   Next Topic Topic: How to flatten the hook hierarchy when using Generic Template Class patter

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use