tree.getSelection() returns the type Object. So I have to cast it to the right object before calling repository.remove( .. ) How can I improve this to remove the cast ? Can generics solve it (I'm not generics savvy!) ?
Thanks
Pho
Naseem Khan
Ranch Hand
Joined: Apr 25, 2005
Posts: 809
posted
0
Originally posted by Pho Tek:
tree.getSelection() returns the type Object. So I have to cast it to the right object before calling repository.remove( .. ) How can I improve this to remove the cast ? Can generics solve it (I'm not generics savvy!) ?
Thanks
Pho
improve in terms of what? If you think your code will run fast if you go for generics, then you are wrong. Yes you can use generics here but still in that case the compiler will place implicit cast for you. Its just that you don't have to cast manually as its very annoying, user has to remember what class of the instance method is returning.
Here is the steps for the creating Generic version
1. create Generic class Tree. 2. getSelection() must return the type parameter of the generic class type. 3. Use parameterized Tree<Group> type at the time of instantiation of Tree class instead of raw type Tree. Then this assignment will work Group g = tree.getSelection(); 4. Then you can use this g in remove() mthod as repository.remove(g);
tree.getSelection() returns the type Object. So I have to cast it to the right object before calling repository.remove( .. ) How can I improve this to remove the cast ? Can generics solve it (I'm not generics savvy!) ?
Thanks
Pho
Yes certainly, but not much can be said without more code. In particular, the implementations of each remove method.
There are two rules that definitely hold with one caveat: 1) You can do *anything* without ever using a cast 2) You can do *anything* without ever a) declaring a reference of type Object b) declaring a return type Object c) Using any methods declared in type Object caveat: assuming the only premise is Java itself - with imposed dependencies (for example, parts of the API specification that have no relationship to the language) - either of these rules may break down. Rule 1 is easily achieved (I hope this is obvious), Rule 2 means you can't (and shouldn't anyway) use collection types or the wait/notify mechanism (which can be solved by other means).