java.util.Arrays
helpers
final String[] names = {"Eve", "Aaron", "Paul", "Mandy"};
System.out.println(" toString: " + Arrays.toString(names));
Arrays.sort(names);
System.out.println("sort|toString: " + Arrays.toString(names));
Result:
toString: [Eve, Aaron, Paul, Mandy] sort|toString: [Aaron, Eve, Mandy, Paul]
final String[] names = {"Aaron", "Eve", "Mandy", "Paul"};
// Precondition: Array must be ordered!
...println("sort|find(Mand): " + Arrays.binarySearch(names, "Mand"));
...println("sort|find(Mandy): " + Arrays.binarySearch(names, "Mandy"));
...println("sort|find(Mandyer): " + Arrays.binarySearch(names, "Mandyer"));
Result:
sort|find(Mand): -3 sort|find(Mandy): 2 sort|find(Mandyer): -4
No. 147
Understanding search results
Q: |
Read the Javadoc™ of In particular give a detailed account explaining the two negative values -3 and -4. |
||||||||||
A: |
The input array reads
A positive return value conveys:
Searching for Negative return values actually also provide two types of information:
In the given example hypothetically inserting the string
{"Aaron", "Eva", "Mand", "Mandy", "Paul"} This insertion point's index is 2 corresponding to the third
array element. According to the The observed return value of -4 when searching for "Mandyer" corresponds to insertion index 3: {"Aaron", "Eva", "Mandy", "Mandyer", "Paul"} Subtracting -1 is being required for conveying the «not in
list» information under all circumstances. Otherwise not finding
and hypothetically inserting e.g. |
final String[] names =
{"Eve", "Aaron", "Paul", "Mandy"};
System.out.println("toString: " +
Arrays.toString(names));
Arrays.fill(names, "N.N");
System.out.println("toString: " +
Arrays.toString(names)); |
toString: [Eve, Aaron, Paul, Mandy] toString: [N.N, N.N, N.N, N.N] |
final String[] names = {"Eve", "Aaron", "Paul", "Mandy"};
final String[] lastTwoNames = Arrays.copyOfRange(names, 2, 6);
System.out.println("toString: " + Arrays.toString(lastTwoNames));
Result:
toString: [Paul, Mandy, null, null]
final String[]
l1 = {new String("Eve"), new String("Aaron"),
new String("Paul"), new String("Mandy")},
l2 = {new String("Eve"), new String("Aaron"),
new String("Paul"), new String("Mandy")},
l3 = {new String("Eve"), new String("Aaron"),
new String("Paul"), new String("Mobile")};
System.out.println("l1.equals(l2):" + Arrays.equals(l1, l2));
System.out.println("l1.equals(l3):" + Arrays.equals(l1, l3));
Result:
l1.equals(l2):true l1.equals(l3):false