Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #34722

Re: mollifying generics

From Daniel Pitts <usenet@coloraura.com>
Newsgroups comp.lang.java.programmer
Subject Re: mollifying generics
Date 2016-06-29 13:43 -0700
Organization A noiseless patient Spider
Message-ID <nl1btn$rqt$1@dont-email.me> (permalink)
References <o907nblakke2c75jrjdbav4pauap3jihg9@4ax.com>

Show all headers | View raw


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.

Back to comp.lang.java.programmer | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


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