在与 instantiation/initialization 相同的行中对数组进行排序
sorting an array in the same line as instantiation/initialization
如果给定一个ints
的数组:
int[] age = new int [] {32, 25, 56, 56, 12, 20, 22, 19, 54, 22};
有没有办法在与instantiation/initialization相同的行中排序(最低-最高),这样年龄的元素就是:12, 19, 20, 22...
?
不在同一行。
但你可以这样做:
public static int[] sort(int[] a) {
Arrays.sort(a);
return a;
}
// ...
int[] age = sort(new int[] {32, 25, 56, 56, 12, 20, 22, 19, 54, 22});
一行不是重要目标:
技术上:
int[] age = new int [] {32, 25, 56, 56, 12, 20, 22, 19, 54, 22}; Arrays.sort(age);
是一行,但我不认为那是你想要的。
暗示你想要它 inline
这是一个有问题的目标,尤其是在 Java.
内联与单线
这个有效,但比两行代码更复杂,而且效率也更低,因为它必须装箱所有东西。
@Nonnull public static <T> T[] sort(@Nonnull final T[] array) { Arrays.sort(array); return array; }
您可以这样称呼它:
public static void main(String[] args)
{
System.out.println(Arrays.toString(sort(new Integer[]{32, 25, 56, 56, 12, 20, 22, 19, 54, 22})));
}
输出:
[12, 19, 20, 22, 22, 25, 32, 54, 56, 56]
I do not see the usefulness of this simple experience tells you that
one line is never a valid goal.
比较字节码为:
final int[] ints = new int[]{32, 25, 56, 56, 12, 20, 22, 19, 54, 22};
Arrays.sort(ints);
System.out.println(Arrays.toString(ints));
然后尝试证明 节省 一行代码。
如果给定一个ints
的数组:
int[] age = new int [] {32, 25, 56, 56, 12, 20, 22, 19, 54, 22};
有没有办法在与instantiation/initialization相同的行中排序(最低-最高),这样年龄的元素就是:12, 19, 20, 22...
?
不在同一行。
但你可以这样做:
public static int[] sort(int[] a) {
Arrays.sort(a);
return a;
}
// ...
int[] age = sort(new int[] {32, 25, 56, 56, 12, 20, 22, 19, 54, 22});
一行不是重要目标:
技术上:
int[] age = new int [] {32, 25, 56, 56, 12, 20, 22, 19, 54, 22}; Arrays.sort(age);
是一行,但我不认为那是你想要的。
暗示你想要它 inline
这是一个有问题的目标,尤其是在 Java.
内联与单线
这个有效,但比两行代码更复杂,而且效率也更低,因为它必须装箱所有东西。
@Nonnull public static <T> T[] sort(@Nonnull final T[] array) { Arrays.sort(array); return array; }
您可以这样称呼它:
public static void main(String[] args)
{
System.out.println(Arrays.toString(sort(new Integer[]{32, 25, 56, 56, 12, 20, 22, 19, 54, 22})));
}
输出:
[12, 19, 20, 22, 22, 25, 32, 54, 56, 56]
I do not see the usefulness of this simple experience tells you that one line is never a valid goal.
比较字节码为:
final int[] ints = new int[]{32, 25, 56, 56, 12, 20, 22, 19, 54, 22};
Arrays.sort(ints);
System.out.println(Arrays.toString(ints));
然后尝试证明 节省 一行代码。