How can i compare a string and a char array in java?

前端 未结 4 1153
余生分开走
余生分开走 2021-01-17 22:56

In my program I\'m trying to compare my char array asterixA[] to string (word) in an if loop like:

if (word.equals(asterixA))

4条回答
  •  情歌与酒
    2021-01-17 23:36

    You seem to be taking the "A String is an array of chars" line too literal. String's equals method states that

    Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

    It all depends of the circumstances, but generally you compare two objects of the same type or two objects belonging to the same hierarchy (sharing a common superclass).

    In this case a String is not a char[], but Java provides mechanisms to go from one to the other, either by doing a String -> char[] transformation with String#toCharArray() or a char[] -> String transformation by passing the char[] as a parameter to String's constructor.

    This way you can compare both objects after either turning your String into a char[] or vice-versa.

提交回复
热议问题