Creating a type-safe Cloneable with generics?

M

Malcolm Ryan

Is it possible to create a type-safe Cloneable interface with generics
in Java 1.5? I want to do something like this:

interface MyCloneable<T> {
public T myClone();
}

class SomeClass implements MyCloneable<SomeClass> {

SomeClass myClone() {
SomeClass clone = new SomeClass();
// ... clone fields ...
return clone;
}
}

So that elsewhere I can do:

SomeClass thing = new SomeClass();
SomeClass clone = thing.myClone();

and know that the clone is of SomeClass, because thing is of
SomeClass. (This is something that has always annoyed me about the
standard clone method.)

When I do this, eclipse 3.1 gives me a type safety warning:

"The return type SomeClass of the method myClone() of type SomeClass
needs unchecked conversion to conform to the return type T of
inherited method."

What does this mean? It doesn't seem to affect the correctness of my
code, and I don't get this warning if I just compile with the Sun
compiler. Can I safely ignore it? Or is there a better way?

Malcolm
 
A

Aquila Deus

Malcolm Ryan wrote:

My code compiles without any warning:


public interface MyCloneable<T> extends java.lang.Cloneable
{
public abstract T clone();
}


public class MyObj implements MyCloneable<MyObj>
{
public MyObj clone() { return new MyObj(); }
}
 
G

ghstark

I have what I think is a related problem since I'm getting the same
warning from Eclipse (Version: 3.1.0 Build id: 200412162000).
What I'm trying to do is write a class that implements the
Iterator<String> interface.

Here is the entire class:
----------------------------------
import java.util.Iterator;

public class MessageIterator implements Iterator<String>
{
public boolean hasNext() { return false; }

public String next() { return null; }

public void remove() {}
}

I get the warning for the next() method.
 
G

Greg Stark

OK, I figured out how to make the error go away. I guess I don't
understand the subtleties of generics quite yet because I'm not sure
why it works.

It turns out if my class declaration starts out as

public class MessageIterator<String> implements Iterator<String>

I don't get the warning. Also, if Malcolm's class is declared as

class SomeClass<SomeClass> implements MyCloneable<SomeClass>
the warning disappears. But it looks ugly and wrong.
 
G

Greg Stark

It is wrong. I'm just creating a new generic type with the type
variable 'String'. It's exactly as if I did

public class MessageIterator<T> implements Iterator<T> .
I will now stop responding to my own posts.
Thank you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top