4

This SO discussion proposes the following idiom:

public interface IComparable<T extends IComparable<T>> {
    int compare(T t);
}

which then allows:

public class Foo implements IComparable<Foo> {
    public int compare(Foo foo) {
        return 0;
    }
}

However, this idiom allows more than just the above as the following code compiles as well:

class A implements IComparable<A> {
    public int compare(A a) {return 0;}
}

public class Foo implements IComparable<A> {

    public int compare(A a) {
        return 0;
    }
}

Therefore (unless I've misunderstood something) the original idiom doesn't really buy anything more compared to the far less dramatic:

public interface IComparesWith<T> {
    int compare(T t);
}

public class A implements IComparesWith<A> {
    public int compare(A a) {...}
}

So, is there a way to actually declare an interface such that whatever class declares to implement it has a method to compare with objects of its own class, without any loopholes such the one above?

I obviously could't post the above as a comment hence I created a new post.

2

5 Answers 5

6

No, that sort of restriction is not possible with the generics as written. Your assessment seems correct to me.

0
5

You are correct: this idiom does not prevent classes from being compared to different classes. All it does is ensure that the compared object also implements the same interface. If there is a requirement to only compare the same types, that can be enforced by the implementing class.

What you call a "loophole" is what I would call "intentionally doing something you don't want to do".

Foo objects can be compared to A objects IF such behavior is desired.

This is a feature, not a loophole.

If you want Foo to be comparable to other Foos, you should define Foo to implement IComparable<Foo>.

If you don't want Foo to be comparable to A, then you shouldn't define Foo to implement IComaparable<A>. Why would anybody do that unless they were trying to write broken code on purpose?

The actual answer to your question has already been provided by @caskey:

"No, you can't do what you want using interfaces in Java. [You have to do it with classes]."

There is one thing that you missed:

Therefore (unless I've misunderstood something) the original idiom doesn't really buy anything more compared to the far less dramatic:

public interface IComparable<T>

The original idiom does buy you something. It enforces that the compared object must implement IComparable. The less dramatic example would allow you to compare implementing classes to any object without restriction. So... The compiler would allow you to specify Long, or InputStream, or LinkedHashSet<Byte[]>, or anything at all as a type parameter.

When you look at it that way, it's easy to see why this idiom is so common.

3

Therefore (unless I've misunderstood something) the original idiom doesn't really buy anything more compared to the far less dramatic:

It does buy something, but it's a different thing than what you're thinking of. And when someone writes that, 99.9% of the time it is not what they are trying to buy.

So, is there a way to actually declare an interface such that whatever class declares to implement it has a method to compare with objects of its own class, without any loopholes such the one above?

No. Because it's not useful in terms of type safety. There's nothing wrong with the public class Foo implements IComparable<A> -- it's perfectly type safe. If someone wants to make a Foo that can safely compare to A in some way, then that's great. I agree with jahroy'a answer -- it's not a "loophole"; it's a feature. Why not make it more general, as long as it's safe? It doesn't get in the way of anything you're doing. If you want to make all your classes compare to themselves, that's fine too. Everything is fine, as long as it's type safe.

The only place where you should care about the relationship about a type and the type parameter with which it implements IComparable is where you use it, because that place may legitimately have a need for such a relationship. So in that place (a generic class or generic method which is parameterized by a comparable type), we can easily bound the type variable that represents the comparable type like this: T extends IComparable<? super T>, allowing us to guarantee that T can compare to itself.

3
  • The semantics of Comparable dictates that if class A implements Comparable<B>, B must be A. If a1 can be compared to b, and a2 can be compared to b, a1 must be able to be compared to a2, therefore A must be a Comparable<A>. Why not relax the semantics of Comparable? Because we want it to have certain properties that the use site of Comparable can depend on. A type needs to be general enough to describe a set of objects; it also needs to be specific enough to describe only these objects.
    – ZhongYu
    Sep 1, 2013 at 3:54
  • Comparable is a higher kind of type, it is meant to describe other types that can be compared to themselves. Java type system isn't rich enough to describe that, so we need to resort to extra-linguistic measures, like javadoc, or naming convention. Other languages e.g. Haskell can describe it pretty well.
    – ZhongYu
    Sep 1, 2013 at 4:02
  • "The semantics of Comparable dictates that if class A implements Comparable<B>, B must be A." No it doesn't.
    – user102008
    Sep 1, 2013 at 9:32
-1

Don't use generics:

public interface Foo {
    public void doSomething(Foo foo);
}
5
  • 2
    This works if you don't mind that the implementing class is now comparable to any other implementing class. Aug 31, 2013 at 23:09
  • @ChrisHayes how is "comparable" relevant? The title mentions nothing about comparable, nor does this answer. I have answered the question as stated.
    – Bohemian
    Sep 1, 2013 at 0:24
  • Are we reading the same question? The entire question uses "IComparable" as the example. The actual interface is irrelevant, however. The asker wants a way to force implementations of MyInterface<T> to always be implemented by class T, i.e., to be unable to put any other class in there. Your answer does not accomplish that. Sep 1, 2013 at 7:57
  • As you say, IComoarable is just an example (ie irrelevant). And my point stands: "Don't use generics". I believe that is the problem... The OP is using generics when he shouldn't. I can't understand why this is turning into such a Jihad :/
    – Bohemian
    Sep 1, 2013 at 11:26
  • That is only the answer if you change the question. The correct answer is that the behavior the OP desires is not possible through an interface; you cannot restrict type generics to the type of the class specifying the value for the generic. Whether this is even desirable is addressed by jahroy above, but this answer does not cover its possibility nor its desirability. Sep 1, 2013 at 11:30
-4

Indeed. I'd advocate that we use This as the conventional name for such type parameters

public interface IComparesWith<This> 
{
    int compare(This t);
}

my previous answer: Convenient way to write generic interface that points out to its implementor

7
  • 3
    Note that this is only a convention (of which I never heard before) and not a programming language feature. This has exactly the same functionality as an ordinary T. Aug 31, 2013 at 23:22
  • 2
    It also avoids the convention of using single capital letters to denote generic parameters. Being a single capital letter away from a (very) common keyword may well lead to confusion.
    – caskey
    Aug 31, 2013 at 23:31
  • 1
    Using This as a type parameter achieves nothing and introduces confusion by going against accepted naming conventions. -1
    – jahroy
    Sep 1, 2013 at 0:10
  • 1
    A convention is something people follow. I hope this never becomes a convention (luckily it won't, because it's useless).
    – jahroy
    Sep 1, 2013 at 1:06
  • 1
    @zhong: This is not a workaround. A workaround is an alternate way of accomplishing the same goal. This does not accomplish the goal; there is no compile time restriction on how the interface may be implemented, nor is there even any guidance to classes implementing the interface on how they should use it. A much better way would be to create a Javadoc telling implementers what to do. Sep 1, 2013 at 7:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.