Fill, copy, compare, setAll and stream
java.util.Arrays is a toolbox of ready-made static methods for arrays: print, sort, search, fill, copy, compare, and turn an array into a list or stream. Using it is shorter, faster and less buggy than writing the same loops yourself.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Given {88, 42, 95, 61, 73}, print the scores sorted, the lowest, the highest and the median, using Arrays methods.
Write a program that checks whether two words are anagrams by sorting their characters: convert with toCharArray(), sort both, compare with Arrays.equals. Test "listen"/"silent" and "java"/"lava".
Given the sorted array {10, 20, 30, 40}, use binarySearch to insert 25 at the correct position, producing a new array [10, 20, 25, 30, 40].
Explain it without notes
Which algorithms does Arrays.sort use for primitives and for objects, and why the difference?
Explain the return value of Arrays.binarySearch when the key is not found.
What's the difference between Arrays.asList(arr) and new ArrayList<>(Arrays.asList(arr))?
Why must an array be sorted before calling binarySearch, and what happens if it isn't?
Expected output
fill: [7, 7, 7, 7]
copyOf 3: [1, 2, 3]
copyOf 7: [1, 2, 3, 4, 5, 0, 0]
copyOfRange 1..4: [2, 3, 4]
src == other: false
Arrays.equals: true
setAll: [0, 1, 4, 9, 16, 25]
sum via stream: 15