Casting Generics

Consider the following coding problem

class A { ... }
class B extends A { ... }
List<A> aList = ...
List<B> bList = ...
List<A> getAList() {
    return bList;

}

This doesn't compile. Why? Because while A is a subclass of B, List<A> is not a sublclass of List<B>. Despite that, it's quite common that you'd want to do something like this.  Consider a more concrete example.

interface TreeNode { ... }
interface ContainerTreeNode extends TreeNode {
    List<TreeNode> getChildren();
}

class Tree(TreeNode rootNode) { ... }

To make themselves tree-storable, other classes just implement TreeNode or ContainerTreeNode. The problem is in the implementation of ContainerTreeNode. For example,

class Employee implements TreeNode { ... }
class Manager implements ContainerTreeNode {
    List<Employee> employees ...;
    ... 
    List<TreeNode> getChildren() {
        return employees;
   }
}

You'd like to be able to do this, but it won't compile for the reasons stated above. The solution is to use the <? extends T> idiom. Declare getChildren() as such,

 List<? extends TreeNode> getChildren();
Comments:

Alain commented on my previous post that the solution there was problematic as it allowed access to arbitrary view which may depend on objects being set up in other views

Posted by links of london on December 13, 2009 at 02:02 PM PST #

jean style jean style jeans stylejeans style mens jean style mens jean style skinny jean style skinny jean style blue jeans style blue jeans style seven jeans style seven jeans style new jean style new jean style latest jean style latest jean style jeans styles jeans styles boy style jeans boy style jeans men jean style men jean style jean style 

Posted by jean style on December 17, 2009 at 02:19 PM PST #

The select items have object values. http://www.watchgy.com All is good. When I submit the form, I see "Validation Error: Value is not valid". My first reaction was that I didn't have any validation on the page, so how could a value be not valid? http://www.watchgy.com/tag-heuer-c-24.html
http://www.watchgy.com/rolex-submariner-c-8.html

Posted by Tag Heuer Watches on December 29, 2009 at 12:23 AM PST #

Post a Comment:
  • HTML Syntax: NOT allowed
About

jtb

Search

Categories
Archives
« July 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  
       
Today