Reputation: 137
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
Upvotes: 0
Views: 1171
Reputation: 1975
Arrays.sort()
method does not return the array;
Do this:
Arrays.sort(arr1);
Arrays.sort(arr2);
if (Arrays.equals(arr1, arr2)) {
// rest of code
Upvotes: 3
Reputation: 66637
Arrays.sort returns void
type. You need valid array type to use Arrays.equals(int[] a,
int[] a2)
Upvotes: 2