A new helper method Arrays.asArray

Remi Forax forax at univ-mlv.fr
Tue Jun 14 19:43:24 UTC 2016


Hi Timo,
your implementation can not use @SafeVarargs because you leak the array (you return it) so you're code is not safe because you can not be sure that the resulting array will not be modified after the call to asArray.

Louis, because you can not create an array of parametrized type in Java :)

Here, the easy solution is to not create an array but a List,
  List<Comparator<Object>> list = List.of(sort0, sort1);
or
  List<Comparator<Object>> list = Arrays.asList(sort0, sort1);
depending if you want a mutable List (but with a fixed size) or an immutable one.

cheers,
Rémi

----- Mail original -----
> De: "Louis Wasserman" <lowasser at google.com>
> À: "timo kinnunen" <timo.kinnunen at gmail.com>, "core-libs-dev" <core-libs-dev at openjdk.java.net>
> Envoyé: Mardi 14 Juin 2016 19:47:23
> Objet: Re: A new helper method Arrays.asArray
> 
> Why would you not just write new Object[] {sort0, sort1, sort2, sort3}?
> 
> On Tue, Jun 14, 2016, 10:35 AM <timo.kinnunen at gmail.com> wrote:
> 
> >
> > Hi,
> >
> > I have found that many times I need to write this simple helper method:
> >
> >         public static @SafeVarargs <T> T[] asArray(T… ts) { return ts; }
> >
> >
> > I usually need this when I have several implementations I’m comparing and
> > I want to change the code for observing one of them to observing two or
> > more of them in sequence. I feel that in this case switching from operating
> > on one object to operating on an unknown List implementation (from
> > Arrays.asList) is a too drastic change when all I need is put a for-loop
> > around some code and iterate.
> >
> > The code for which I have to write this method is often some variation of
> > something like this:
> >
> >        Comparator<Object> sort1 = (x, y) -> (Integer) x - (Integer) y;
> >        Comparator<Object> sort0 = (x, y) -> (int) (Math.pow((Integer) x,
> > 2.0) - Math.pow((Integer) y, 2.0));
> >
> >        // Have to use a helper method here
> >        Comparator<Object>[] sorts = asArray(sort0, sort1, sort2, sort3);
> >
> >
> > Please consider and add this simple method to Arrays.
> >
> >
> >
> > --
> > Have a nice day,
> > Timo
> >
> > Sent from Mail for Windows 10
> >
> >
> 


More information about the core-libs-dev mailing list