Sorting Strings and extracting common elements of two String arrays in Java

前端 未结 8 1025
南方客
南方客 2020-12-22 12:01

I was asked to write down a Java function sharedStr that by given 2 sorted arrays of Strings, returns the number of Strings that appea

8条回答
  •  醉梦人生
    2020-12-22 12:13

    1. Strings are usually ordered in lexicographic fashion (alphabetical). However, as long as the ordering is consistent, the exact ordering method is not important for this problem (they could be reverse sorted for instance).
    2. Java compares objects (not object references) using .equals() (for boolean) or .compareTo() (for relational comparison) For instance:

    .

    String a = "Hello";
    a.equals("Hello"); // true
    String b = "Not hi";
    b.equals(a); // false
    

    Be careful accidentally using == - for constant strings, due to VM designs, it may actually say two Strings are equal, as they are in fact the same object.

提交回复
热议问题