Issue with Comparator.comparing

B. Blaser bsrbnd at gmail.com
Mon Dec 17 14:53:04 UTC 2018


On Mon, 17 Dec 2018 at 13:49, Maurizio Cimadamore
<maurizio.cimadamore at oracle.com> wrote:
> [...]
> Challenge: can you find an example which ends up with same behavior
> (ClassCastException) that does _not_ involve method references and/or
> lambdas?
>
> Maurizio

I like challenges, but I agree this one is hard as it involves a raw
'Foo3' to simulate the capture side-effect as here under.

Thoughts?
Bernard

import java.util.*;
import java.util.stream.*;
import java.util.function.*;

class Foo3<T extends Comparable<T>> {

    static Foo3<String> S = new Foo3<>("");
    static Foo3<Integer> I = new Foo3<>(42);

    private T t;

    Foo3(T t) {
        this.t = t;
    }

    T t() {
        return t;
    }

    public static void main(String[] args) {
        List<Foo3<?>> l = new ArrayList<>();
        l.add(S);
        l.add(I);

        Comparator<? super Foo3<?>> comp = new Comparator<Foo3>() {
            public int compare(Foo3 f1, Foo3 f2) {
                return f1.t().compareTo(f2.t());
            }
        };
        Collections.sort(l, comp);
    }
}


More information about the compiler-dev mailing list