I need to check if the elements in the arraylist are arranged in ascending order or not. and when i use this code, the output shows "not sorted" even for a sorted array. why is it showing the wrong output?**
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> array1 = new ArrayList<>();
ArrayList<Integer> array2 = new ArrayList<>();
int n = sc.nextInt();
for (int i = 0; i < n; i ) {
array1.add(i, sc.nextInt());
array2.add(i, array1.get(i));
}
Collections.sort(array1);
if (array1 == array2) {
System.out.println("sorted");
}
else {
System.out.println("not sorted");
}
}
CodePudding user response:
"==" checks weather two object identical that means it check weather they point to the same memory location. If your array1 is on @698 location your array2 will be somewhere else like @700 ,so they don't point to the same location that's why it shows they are not equal. You better check it on this way:
if (array1.equals(array2)){
System.out.println("They are equal");
} else{
System.out.println("They are not equal");
Then it shows the right answer
CodePudding user response:
The error using ==
instead of equals
is clear. For arrays there is Arrays.equals(int[] lhs, int[] rhs)
.
However sort
does to much work, and needs a copy of the array.
Better:
static boolean isSorted(List<Integer> list) {
for (int i = 1; i < list.size(); i) {
if (list.get(i).compareTo(list.get(i - 1)) < 0) {
return false;
}
}
return true;
}
Could even be more general:
static <T extends Comparable<T>> boolean isSorted(List<T> list) {