Recording Sheet of Some Pre-written Methods

Expected to be a useful reference document.
Shall keep updating.

String Methods

String is final and ummutable, methods apply to string will return a new string.

  • .length() return total number of characters
  • .toUpperCase()/.toLowerCase() return string with uppercase/lowercase characters
  • .substring(i) return a string start from ith character (count from 0)
  • .substring(m,n) return a string start from mth and end at nth character (nth character is not included)
  • .concat(char[]) concatenates char[] to end of this string, null arguments will throw NullPointerException
    * to add null to a String, can just use `+`
    
  • .charAt(i) return ith character of the string (char is not a string object)
  • .indexOf('char') return the index of the 1st ‘char’ in the string
  • .replace('oldchar', 'newchar') return a new string with replacing of ALL oldchar
  • .equals("string") return true or false if their values are equal or not
  • .equalsIgnoreCase("string") will ingore the upper or lower case
  • .toCharArray() to return a array to characters from the string
  • .isEmpty() return true for empty string
  • .startsWith("string")/.endsWith("string") return true if the string starts of ends with “string”
  • .contains(CharSequences s) return true only if the string contains the specified sequence of char values
  • .trim() return a new copy of the string with leading and trailing whitespace ommited
  • .split("separator") returns array of substrings, based on the separator
    for example:

    1
    2
    String names = "Peter, John, Andy, David";
    String[] splitNames = names.split(", ");
    splitNames will be {"Peter", "John", "Andy", "David"};
    

StringBuilder Methods

StringBuilder is mutable and more suitable for creating temporary strings

  • .append() to add a string to end of the StringBuilder, for null argument, “null” will be appended
  • .insert(index, char[]) to insert the char[] at the index, won’t compile to null
  • .reverse() to reverse the chars in the StringBuilder
  • .delete(int start, int end) to delete chars in the StringBuilder
    * `.deleteCharAt(int index)` to delete char at the index
    
  • .replace(int start, int end, String replacement) to replace part of the StringBuilder
  • –methods below cannot be chanined–
  • .setLength(int) will set a new StringBuilder with the length and copy contents into it
  • .subString(int start) will return a new String

Math Methods

  • Math.round(x) can be used to round a number, will return long type number (123.4 ->123 ; 123.5->124)
    * For X.5, banker's round is applied, will round to even number (0.5->0, 1.5->2)
    
  • Math.ceil(x) to return the smallest double that is larger than the number (123.4 -> 124.0)
  • Math.sqrt(x) return the square root
  • Math.hypot(x,y) return sqrt (x^2 + y^2)
  • Math.PI return the value of PI (3.1415926….)
  • Math.random() return a random double between 0 and 1

Wrapper Methods

Shall be applicable for other wrapper class (Byte/Short/Long/Float/Double/Boolean)

  • Integer(string/int) constructor for wrapper class, no non-args constructor for wrapper class
  • Integer.parseInt(string) to convert from a string, can only take string as arg,the return type is primitive
  • Integer.valueOf(string/number) to return the Integer type of int (unnecessary with autoboxing)
  • Integer.toString(number) to convert a number to String, will throw error for ‘null’ argument
  • Integer.MAX_VALUE to return the max value of the object
  • Integer.MIN_VALUE to return the min value of the object
  • Integer.toBinaryString(number) to return the binary type of number (works for Integer only)
  • intObject.intValue() to return the int of a Integer, non-static method (unnecessary with unboxing)

Character Methods

  • Character.toLowerCase(c) to convert char c to lowercase

Object Methods

  • String.format("format_specifiers", data) to return the data with format as String
  • String.valueOf(number) to return the String type of data, will give “null” for ‘null’ argument
  • obj instanceof Object will return true if obj is an instance of Object, treated as an operator
  • obj1.equals(obj2) will return true only if obj1 and obj2 point to the same object
  • obj1.compareTo(obj2) will return a integer result of (obj1 - obj2), the compare is based on the unicode value of each character
    * " " <- (0~9) <- (A~Z) <- (a~z)
    * negative means obj2 is "bigger", the order is obj1, ... , obj2, ...
    * positive means ojb1 is "bigger", the order is obj2, ... , obj1, ...
    

Array Methods

import before use import java.util.Arrays;

  • Arrays.asList(array) converts the array into a List(not arrayList)
  • Arrays.equals(arr1, arr2) return true only if both value and order are same
  • Arrays.copyOf(arr, length of new array) will copy the array with a new length, useful for adjustment of array size
  • Arrays.copyOfRange(source, m ,n) will return elements from index m to index (n-1), index n is not copied
  • Arrays.toString(arr) return the contents of an array
  • Arrays.sort(arr) will sort the array in ascending order
  • Arrays.binarySearch(arr, value) will return the index of the value for a sorted array, if not found, will return -i, (i-1) is the supposed index
  • .length return the size of a array, no parenthesis

Class Methods

  • .getClass() to return the current class name
    * Add ons
            * `.getSuperclass()` to return the super class name
            * `.getSimpleName()` to return the simple name 
    

ArrayList Methods

The following methods are pre-written, typical usage will be nameOfArrayList.method()

  • .add(element), to add members to a list, return true when list had changed
    • .add(index, element) to add element at specific position, no return
  • .addAll(collection) to append all element of an arrayList to end of the list
  • .set(index, element) to replace element at specific position, return the element that was replaced
  • .remove(index) to remove element at specific position, return the element that has been removed
  • .remove(element) to remove the first occurrence of an element, will return true when list had changed
  • .removaAll(collection) to remove all elements that are contained in the collection
  • .clear() to remove all elements from the list, no return
  • .get(index) to get element at specific position
  • .size() to get the number of elements in the list
  • .trimToSize() to trim all unused space
  • .ensureCapacity(int) to change the capacity
  • .contains(element) to check if list contains the element, will return true / false
  • .indexOf(element) to get the index of the first occurrence of an element, will return -1 if element does not exist
  • .subList(m,n) return a List of elements between index m and n (n is exclusive), change on subList applies to original list
  • .toArray() returns an array of object containing all the elements, from first to last element
    * to pass the data to an array, use `.toArray(arrayName)`
    
  • .toString() return the value of the arraylist as an array

LinkedList Methods

Share most methods of ArrayList Methods, but have queue and deque interfaces with following methods

  • .pull() return the first element (head) and remove it from the list
  • .peek() return the first element, will return null for empty list
  • .getFirst() return the first element, will give NoSuchElementException for empty list
  • .getLast() return the last element, will give NoSuchElementExcepetion for empty list
  • Complete list of all LinkedList methods at https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html

Iterator Methods

Iterator is an interface that allows us to traverse the collection, access the data element and remove the data elements of the collection
Need to import before use, curser will start from the head of the first element

  • Iterator iterator = list.iterator() Iterator to traverse the list
  • .hasNext() return true if the Iterator has more element to iterate
  • .next() return the next element in the collection
  • .remove() remove the current element in the collection, will throw exception if called before invoke .next()

ListIterator Methods

A kind of Iterator that allows traverse collection in both direction
Need to import before use, curser will start from the head of the first element

  • .add(object) will insert object before the element that is returned by the .next()
  • .hasPrevious() return true if the list has a pervious element
  • .previous() return the previous element of the list
  • .remove() remove the current element from the list, need to invoke .next() or .previous() first

LocalDate/LocalTime/LocalDateTime methods (JAVA 8)

Belongs java.time package, all date/time objects are immutable
none of the classes have a public constructor, cannot create using new operator

  • .now() returns an instance of the object that represents current data or time
  • static LocalDate of() to create an object for any date
    * `.of(int year, int month, int dayOfMonth)`
    * `.of(int year, Month month, int dayOfMonth)`
    
  • static LocalTime of() to create an object for any time
    * `.of(int hour, int minute, int second, int nanoSecond)`, second and nanoSecond not compulsory
    
  • static LocalDateTime of() to create an object for any date and time
    * `.of(LocalDate date, LocalTime time)`, or use `year, month, day, hour, minute, second, nanoSecond`
    
  • .from(LocalDate/LocalTime/LocalDateTime) create an object from the temporal accessor
    * Cannot create LocalDate from LocalTime/LocalDateTime
    
  • .plus/minusXXX(amount) to modify the proterties
  • .plus/minus(TemporalAmount amount) to modify a amount of temporal, eg. Period.of(0,0,10) for 10 days
  • .plus/minus(long amount, TemporalUnit), eg. (10, ChronoUnit.DAYS) for 10 days
  • .withXXX(amount) to modify the property directly
  • .atTime()/atDate() to add a time/date component to existing date/time, returns a refrence of different type

  • static LocalDate/LocalTime/LocalDateTime parse(CharSequence text) to convert String into date/time

    * `parse(CharSequence text, DateTimeFormatter formatter)` to apply a formatter
    
  • .equals() return true for same class and same content

  • .compareTo() return an int, negative if argument is later
  • .isAfter()/isBefore() return true if is after/before the argument
  • .isEqual() return true if the date is equal
    * `.isXXX()` ignore the calendar system
    

Period/Duration methods (JAVA 8)

Belongs java.time package, period is date(Y-M-D) based, duration is time(h:m:s) based
cannot create using new operator,

  • .ZERO represents a period of zero
  • static Period of() to create an object for any period/duration
    * `of(int years, int months, int days)`
    * `ofDays/ofMonth/ofWeeks/ofYears()` 
    
  • .withXXXs(amount) to modify the property
    `.withXXXs(amount).negated()` to return a new period with amount for each component negated
    
  • .parse("PnYnMnWnD") to parse string into period, n is number, case of letter not imprtant
  • .equals() return true if all three components are equal
  • .isZero() return true if all three components are zero
  • .isNegative() return true if any of the compinent is negative

DataTimeFormatter Class (JAVA 8)

import java.time.format.DateTimeFormatter before use

  • DataTimeFormatter.ofPattern("MMM/dd/yy") to create a formatter
    * Month and Hour are upper case, the rest are lower case
    * ISO formatter are __yyyy-mMM-ddTHH:mm:ss__
    
  • dtf.format(Temporal Accessor) returns formated string
  • static DataTimeFormatter ofLocalizedDate/Time/DateTime(FormatStyle) create a build-in formatter
    * `ofLocalizedDateTime(dateStyle, timeStyle)` 
    * FormatStyle is an enum with `FULL/LONG/MEDIUM/SHORT` four valuse, need to import java.time.format.FormatStyle;
    * FormatStyle.FULL/LONG will throw Exception for LocalDateTime and LocalTime