Java Complete Functions CheatSheet
Java Complete Functions CheatSheet
The `toCharArray()` method in Java's String class converts the string into an array of characters. This can be particularly useful when detailed manipulation of individual characters is required, as arrays provide mutable elements that can be indexed and modified directly. For instance, a task that requires reversing a string without using additional libraries could first convert the string to a character array, reverse the elements using an algorithm (like two-pointer swap), and then recombine them into a string if needed. This method is also useful for processing each character separately for tasks such as encoding transformations and checksum calculations .
The `String.split(String regex)` method is particularly suitable for cases where a string needs to be divided into multiple substrings based on specific delimiters characterized by regular expressions. It is highly effective when the delimiters are variable or follow complex patterns, allowing for immediate decomposition into an array of strings, which can then be further processed. It acts efficiently when handling input parsing tasks such as reading comma-separated values or splitting sentences by punctuation. In contrast, `StringBuilder` is more suited for iterative character modifications and re-constructions rather than parsing-based decompositions .
The `Arrays.binarySearch(array, key)` function performs a binary search on a sorted array to find the specified `key`. It uses a divide-and-conquer approach, repeatedly dividing the search interval in half. If the value of the `key` is less than the middle element of the interval, it narrows the interval to the lower half. Otherwise, it reduces it to the upper half, until the `key` is found or the interval is empty. The efficiency and algorithm depend on the array being sorted; otherwise, it might not find the correct element or return an unexpected index because the assumptions of ordering used by the binary search algorithm are violated. This is why pre-sorting with `Arrays.sort()` is necessary for accurate results .
The `StringBuilder.replace(int start, int end, String str)` method replaces the characters in a substring of the `StringBuilder` with specified characters. The substring begins at the `start` index and extends to the `end` index, exclusive. This method is particularly useful for dynamically modifying strings without creating new string objects in memory, as would be required by String manipulation. For example, in a `StringBuilder` containing "Hello World", calling `sb.replace(6, 11, "Java")` would alter the string to "Hello Java", effectively substituting "World" with "Java" .
The `ArrayList.addAll(Collection<? extends E> c)` method allows for the consolidation of elements from one collection into another, enhancing list operations by enabling bulk addition. This is advantageous as it simplifies combining collections, reduces overhead compared to adding elements individually in a loop, and maintains operation atomicity. In scenarios requiring the union of two lists—such as consolidating user data or merging search results—using `addAll` increases efficiency and cleanliness of code by minimizing manual iterations, thus enhancing readability and performance .
The `parallelSort` method in the Java Arrays Utility Class is designed for performing a parallel sort on large arrays, which can provide performance improvements by taking advantage of multi-core processors. It sorts the array elements concurrently in separate threads, making it efficient for large datasets. In contrast, `sort` uses a sequential algorithm and is generally suitable for small to moderately sized arrays where the overhead of parallelism doesn't justify potential gains. `parallelSort` should be considered when dealing with large data sets where performance is crucial and the overhead of managing multiple threads is outweighed by the speed of parallel processing .
The `retainAll(Collection<?> c)` method in an ArrayList modifies the list it is called on by keeping only the elements that are also contained in the specified collection `c`, effectively intersecting the two collections. This operation can be useful in filtering a list against a set of permissible values. For example, if you have a list of integers representing IDs and want to keep only those that are approved, provided in another list, calling `retainAll` will efficiently filter the original list. This is especially useful in data processing where you need to match records with allowed keys or validate entries against a whitelist .
The `substring(int start, int end)` method in Java's String class returns a new string that is a subset of the original string, starting from index `start` and ending at index `end`, exclusive. This means the character at the `end` index is not included in the resulting substring. Proper bounds checking should be done to ensure that `start` is non-negative, `start` does not exceed the length of the string, and `end` is greater than `start` but less than or equal to the length of the string. Failure to do so can result in a `StringIndexOutOfBoundsException`. For example, for the string "hello", `s.substring(1, 4)` returns "ell" .
The `equals(String s)` method in Java performs a case-sensitive comparison between two strings, meaning it returns true only if the characters match exactly, including their case. This is appropriate when distinct character cases carry significance, such as passwords or case-sensitive file paths. On the other hand, `equalsIgnoreCase(String s)` performs a case-insensitive comparison, ignoring character case differences. This is particularly useful in scenarios like input validation (e.g., usernames, commands) where users might not adhere to case consistency. Choosing between these methods impacts the logic of applications, especially in contexts where case sensitivity might alter intended functionalities .
The `replaceAll(String regex, String replacement)` method is more effective than `replace(char oldChar, char newChar)` when complex pattern matching is needed. `replaceAll` utilizes regular expressions, allowing for more sophisticated replacements based on patterns rather than just replacing specific characters. This is particularly useful in scenarios where multiple characters fit a specific pattern. For instance, using `replaceAll("\\d", "")` on "a1b2c3" removes all digits, resulting in "abc" . The `replace` method only substitutes all occurrences of a single character with another character and doesn't support regular expressions.