Re: More Generics warnings.
Roedy Green wrote:
On Tue, 01 Jan 2008 04:50:13 -0500, Lew <lew@lewscanon.com> wrote,
quoted or indirectly quoted someone who said :
Roedy Green wrote:
Any hints would be appreciated, including ways to think about generics
so they make sense.
I think you only have to make the class itself generic - see if my mods do any
good. I haven't tried it yet.
It did not quite work, but when I replaced a couple of Objects with T,
off it went, no errors. Thanks!
You mean as in
T pivot = userArray[ lo ];
?
I also had a variable named T (violating the convention) that had to
be renamed.
I saw that. I figured you'd catch it pretty quickly. The version I reposted
had at least some of these changes.
Now if I can only figure out what it means. :-)
I doubt I have Owen's keen grasp, but here's my operational simplification:
1) Any time you see a raw type with any generic anything, get rid of the raw
type. Inverting, that means add a generic decoration to every raw type possible.
public static <T> void sort( T[] userArray, Comparator<? super T>
comparator )
{
QuickSort h = new QuickSort();
h.comparator = comparator;
where the member is defined
private Comparator comparator;
Rule of thumb moves a T into that:
private Comparator <? super T> comparator;
Now the signature matches that of the argument to the static method.
2) A generic member means it belongs to a generic class.
That means
public class QuickSort
becomes
public class QuickSort <T>
at least at first. (Do you want to restrict T? In this case, not.)
3) Anywhere inside the class (with certain @Override exceptions) that you see
'Object' make it 'T'.
private Object[] userArray;
becomes
private T [] userArray;
Whoa! This brings up
4) Generics and arrays don't mix.
But here they do. Why?
5) Inside the warm nest of a generic class you can declare an array statically
as the generic type. Here I mean "statically" not as in "static" but as
opposed to "dynamically" - i.e., "compile-time".
That's enough to make all the changes except renaming variable T. The
compiler alerts you to that if you don't catch it, I think.
I actually named the parametrized type "T" before I realized there was a
variable by that name.
I hope my simplifications prove useful. I am not fully comfortable with
generics yet, although it helps to remember
6) Generics only exist at compile time.
This helps distinguish the use cases for, e.g., using a generic array and when
it doesn't work.
--
Lew