-1

This is a method I was supposed to write. It takes two Strings and is supposed to return true if they are anagrams. Also the sorting is demanded.

I'm not allowed to use imports, just used one to see if it sorts correctly. However I don't understand why it still returns false? I read somewhere als that (ArrayA == ArrayB) works as comparison?

public static boolean anagramCheck (String a, String b) {

    String[] conA = a.toLowerCase().split("");
    String[] conB = b.toLowerCase().split("");

    //sort A
    for (int i = 0; i < (conA.length-1); i++) {
        for (int j = i + 1; j < conA.length; j++) {

            if (conA[i].compareTo(conA[j]) > 0) {
                String temp = conA[i];
                conA[i] = conA[j];
                conA[j] = temp;


            }
        }
    }

    //sort B
    for (int i = 0; i < conB.length; i++) {
        for (int j = i + 1; j < conB.length; j++) {

            if (conB[i].compareTo(conB[j]) > 0) {
                String temp = conB[i];
                conB[i] = conB[j];
                conB[j] = temp;
            }
        }
    }

    System.out.println(Arrays.toString(conA));
    System.out.println(Arrays.toString(conB));

    boolean result;

    if (conA == conB) {
        result = true;
        return result;
    } else {
        result = false;
        return result;
    }
}
Eritrean
  • 15,851
  • 3
  • 22
  • 28
Merudoo
  • 21
  • 6
  • No `conA == conB` does not work as a comparison (in this situation) – vincrichaud Nov 12 '21 at 16:43
  • 1
    You have to loop through your sorted arrays, and check element by element that they're the same : `conA[i].equals(conB[i])` – vincrichaud Nov 12 '21 at 16:48
  • Does this answer your question? [equals vs Arrays.equals in Java](https://stackoverflow.com/questions/8777257/equals-vs-arrays-equals-in-java) I know it’s not the exact same question. I still think the answers there may serve your purpose too? – Ole V.V. Nov 12 '21 at 16:54
  • Yeah that solved it, in addition with what @vincrichaud said. Thank you very much. – Merudoo Nov 12 '21 at 16:59

1 Answers1

1

Use Arrays.equals. == check equality of object as both are different instance so return false.It is required to compare element by element in array to compare two array equal or not. For loop through array and compare each element.

if (Arrays.equals(conA,conB)) {
        result = true;
        return result;
    } else {
        result = false;
        return result;
    }
gati sahu
  • 2,576
  • 2
  • 10
  • 16