Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does array.sort not work by an array like this?

Tags:

java

arrays

I've just started programming around 2 weeks ago so please don't be too strict :)

I tried to solve a programming exercise to print the 3 largest elememts of an Array but the .sort Method

reports an error and I don't know why. It seems like I have declared my Array in the wrong way but I can't spot the mistake.

public static void main(String[] args) {
    int [] elements = {1, 4, 17, 7, 25, 3, 100};
    int k = 3;
    System.out.println("Original Array: ");
    System.out.println(Arrays.toString(elements));
    System.out.println(k +" largest elements of the said array are:");
    Arrays.sort(elements, Collections.reverseOrder());         
   for (int i = 0; i < k; i++) 
      System.out.print(elements[i] + " ");
}

}

like image 326
Encera Avatar asked Feb 13 '26 17:02

Encera


1 Answers

Because the integers are unboxed and are not objects. They need to be boxed, i.e Integer.

Unboxed

int [] elements = {1, 4, 17, 7, 25, 3, 100};

Boxed

Integer [] elements = {1, 4, 17, 7, 25, 3, 100};

Using Java 8 Streams

       int[] elements = { 1, 4, 17, 7, 25, 3, 100 };

       int[] sortedUnboxed = IntStream.of(elements)
                .boxed()
                .sorted(Comparator.reverseOrder())
                .mapToInt(value -> value)
                .toArray();

        Integer[] sortedBoxed = IntStream.of(elements)
                .boxed()
                .sorted(Comparator.reverseOrder())
                .toArray(Integer[]::new);
like image 86
Jason Avatar answered Feb 16 '26 07:02

Jason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!