Re: [TriJug] Generics Help

"Harold Meder" <[email protected]>
Newsgroups gmane.org.user-groups.trijug.juglist
Message-ID <[email protected]>
The following is not as type safe as you are aiming for, but the warning is
gone.

public class CO
{
    static Cont<CO> getCont(CO c)
    {
        if (c instanceof C1)
            return new D1();
        if (c instanceof C2)
            return new D2();
        throw new Error();
    }

    static
    {
        CO c = new C1(); // or C2
        Cont<CO> cont = getCont(c);
        cont.add(c);
    }
}
class C1 extends CO
{//
}
class C2 extends CO
{//
}
class Cont<T extends CO> {
    void add(T t) {//
        }
}
class D1 extends Cont<CO>
{//
}
class D2 extends Cont<CO>
{//
}


On 3/15/06, cebmailbox-trijug-/[email protected] <cebmailbox-trijug-/[email protected]> wrote:
>
> Anyone know the answer?
>
> Given the following code:
>
> A base class:
>    class C0 {...}
>
> 2 subclasses:
>     class C1 extends C0 {...}
>     class C2 extends C0 {...}
>
> A generic container to hold either:
>     class Cont<T extends C0> {
>         void add(T t) {...}
>     }
>
> 2 specialized containers:
>     class D1 extends Cont<C1> {...}
>     class D2 extends Cont<C2> {...}
>
> *Crucially now* a static method returns the matching container:
>     static Cont getCont(C0 c) {
>         if (c insta! nceof C1)  return new D1();
>         if (c instanceof C2)  return new D2();
>     }
>
> Expected usage:
>     C0 c = new C1();  //or C2
>     getCont(c).add(c);
>
> But compiles with the warning:
>     Type safety: The method add(C0) belongs to the raw type Cont.
> References to generic type Cont<T> should be parameterized.
>
> The above is obviously contrived and there are probably other
> implementations that can get around the warning.  I could also suppress the
> warning.
>
> BUT as a learning exercise, I really want to know if there is any
> change that could be made to the signatures of the classes, the static
> method or the usage that would eliminate the warning.
>
> -Ch! ris
>
>
> _______________________________________________
> Juglist mailing list
> [email protected]
> http://trijug.org/mailman/listinfo/juglist_trijug.org
>
>
>

_______________________________________________
Juglist mailing list
[email protected]
http://trijug.org/mailman/listinfo/juglist_trijug.org
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.