0

I am able to sort arrays, and able to compare arrays in separate steps, but when I attempt to do both in the same line, I get an error. From the Java documentation, the sort method should return an array of the same type passed into it, and the equals method should return a boolean value.

What am I misunderstanding/misusing here?

Here is my code for testing the situation:

import java.util.Arrays;

public class test {

    public static void main(String[] args) {
        int[] arr1 = {2,4,5,3,1};
        int[] arr2 = {4,3,2,1,5};

        if (Arrays.equals(Arrays.sort(arr1), Arrays.sort(arr2))) {  // Problem line
        System.out.println("Same contents");
        }
        else {
        System.out.println("Different contents");
        }
    }
}

As far as I can see, I have created 2 arrays with the same contents. I then call Arrays.equals(), and for its 2 arguments, I pass in the results of calling Arrays.sort() on each array.

When trying to compile, I get the following error:

test.java:9: error: 'void' type not allowed here
        if (Arrays.equals(Arrays.sort(arr1), Arrays.sort(arr2))) {
                                     ^
test.java:9: error: 'void' type not allowed here
        if (Arrays.equals(Arrays.sort(arr1), Arrays.sort(arr2))) {
                                                        ^
2 errors
shell returned 1
2
  • What is the documented return type of Arrays.sort(). The javadoc is your friend. Read it. Commented Mar 7, 2016 at 21:23
  • @JBNizet Yep, that'll do it. I did have a read through it, but obviously confused my self into thinking an array was returned. Thank you. Commented Mar 7, 2016 at 21:30

2 Answers 2

3

Arrays.sort() method does not return the array;

Do this:

Arrays.sort(arr1);
Arrays.sort(arr2);
if (Arrays.equals(arr1, arr2)) {
// rest of code
Sign up to request clarification or add additional context in comments.

Comments

2

Arrays.sort returns void type. You need valid array type to use Arrays.equals(int[] a, int[] a2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.