aspose file tools*
The moose likes Java in General and the fly likes adding parameterized object in a Collection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "adding parameterized object in a Collection" Watch "adding parameterized object in a Collection" New topic
Author

adding parameterized object in a Collection

Mauricio Lopes
Greenhorn

Joined: Aug 04, 2009
Posts: 12
On my way studing AI, I've trying to develop an heuristic search and I come up with the following problem:

I have a fringe in a superclass:



for each different search strategies I have a subclass that instantiate a different kind of fringe, for example:



the add() has a compilation problem:

The method add(capture#2-of ? extends Node<T>) in the type Collection<capture#2-of ? extends Node<T>> is not applicable for the
arguments (Node<T>)

What's happening?
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3402
    
    9
You are trying to add a Node<T> to a collection that holds "something that is a subclass of Node<T>". What if your fringe happens to be an ArrayList<SubNode<T>>? Clearly, you are not allowed to add some Node<T> when it expects a SubNode<T>. One solution is to remove the upper bound on your fringe: simply make it a Collection<Node<T>>.
Mauricio Lopes
Greenhorn

Joined: Aug 04, 2009
Posts: 12
Thanks Stephan!

I've not mentioned that the code was as you told to be a Collection<Node<T>>. But on design progress I needed a subclass of Node<T> called HeuristicNode<T>. Somewhere else I've gonna need to add that subclass object to fringe. That's why the fringe must be as it is declared.

Can imagine any other solution!?
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3402
    
    9
I think the neatest way is to probably just make it a Collection<Node<T>> and then simply add HeuristicNode<T> to it when you need to. Then when you retrieve nodes, simply check whether the node is a HeuristicNode:
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: adding parameterized object in a Collection
 
Similar Threads
override the equals and hashcode
CertPal Q61 - Which will be OVERRIDDEN?
T cannot be resolved to a type
Wildcard Type with Extend - Generics
generics / adding to wildcard Collection