0

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");
    }
}
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
ananya
  • 1
  • 2
    The `==` operator tests that two references both point to the same object. It doesn't test whether two objects are equal. You can compare two lists are equal with the `List.equals()` method -- e.g., `if ( array1.equals( array2 ))`. – Andy Thomas Apr 08 '22 at 20:36
  • Sorting can take O(n log n) or more. You could instead just test for sorted order in O(n). – Andy Thomas Apr 08 '22 at 20:39

2 Answers2

2

"==" 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

2

The error using == instead of equals is clear. For arrays there is Arrays.equals(int[] lhs, int[] rhs).

However sort does too 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) {
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • Do the int array names in **Arrays.equals(int[] lhs, int[] rhs)** mean left-hand side and right-hand side? I am unfamiliar with the **Arrays.equals()** method. Thank you pre-emptively for clarification. – Kemper Lee Apr 09 '22 at 00:44
  • 1
    @KemperLee My ad-hoc naming, yes, left-hand side. Arrays, Collections, Files all are nice utility classes. – Joop Eggen Apr 10 '22 at 01:16