Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.java.programmer > #34723
| From | Daniel Pitts <usenet@coloraura.com> |
|---|---|
| Newsgroups | comp.lang.java.programmer |
| Subject | Re: mollifying generics |
| Date | 2016-06-29 13:47 -0700 |
| Organization | A noiseless patient Spider |
| Message-ID | <nl1c4q$rqt$2@dont-email.me> (permalink) |
| References | <o907nblakke2c75jrjdbav4pauap3jihg9@4ax.com> <nl1btn$rqt$1@dont-email.me> |
On 6/29/16 1:43 PM, Daniel Pitts wrote:
> On 6/29/16 1:11 AM, Roedy Green wrote:
>>
>> Prior to generics, I could say something like this:
>>
>> Comparable a = "abc";
>> Comparable b = "def";
>>
>> or Comparable a = new Long( 2 );
>> Comparable b = new Long ( 4 );
>>
>>
>> int diff = a.compareTo(b);
>>
>> The run time would use the corresponding compareTo method
>>
>> Now generics complains about an unchecked operation.
>>
>> Is there a way to mollify it? I have tried what I thought were the
>> obvious means.
>>
>
> Let's say you used to have this:
>
>
> public void doSomethingWithDiff(Comparable a, Comparable b)
> {
> int diff = a.compareTo(b);
> if (diff < 0) {
> handleLess();
> } else if (diff > 0) {
> handleMore();
> } else {
> handleEqual();
> }
> }
>
> You would want to replace it with:
> public <T> void doSomethingWithDiff(Comparable<T> a, T b)
>
> Or:
> public <T extends Comparable<? super T>> void doSomethingWithDiff(T a,
> T b)
>
> Either one of those will work as a type safe alternative.
>
> You'll have to keep track of the type with generics *or* specifics up to
> that point to have the compiler satisfied.
>
>
You could also more easily not keep track of the type in your client
code, and move that into a separate class:
public class ComparablePair<T extends Comparable<? super T>> {
private final T left;
private final T right;
public ComparablePair(T left, T right) {
this.left = left;
this.right = right;
}
public int compare() {
return left.compareTo(right);
}
}
You could use it then:
ComparablePair<?> pair
= new ComparablePair<>("abc", "def");
ComparablePair<?> anotherPair
= new ComparablePair<>(new Long(2), new Long(4));
Back to comp.lang.java.programmer | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
mollifying generics Roedy Green <inquiry@mindprod.com> - 2016-06-29 01:11 -0700
Re: mollifying generics Andreas Leitgeb <avl@logic.at> - 2016-06-29 08:33 +0000
Re: mollifying generics Daniel Pitts <usenet@coloraura.com> - 2016-06-29 13:43 -0700
Re: mollifying generics Daniel Pitts <usenet@coloraura.com> - 2016-06-29 13:47 -0700
Re: mollifying generics Arne Vajhøj <arne@vajhoej.dk> - 2016-07-05 22:28 -0400
csiph-web