0%

Common Java and Python API

Python

List

  • Can contain objects in different types, size can shrink or grow

  • [] or list() is empty list

    Method Description
    list(seq) create a list from a sequence
    ls.append(x) appends an item
    ls.extend(iterable) appens multiple items
    ls.insert(index, x) if index = 0, inserts at front, ls.insert(len(ls), x) is just ls.append(xs)
    ls.remove(x) removes the first x, if x not in ls, ValueError
    ls.pop([index]) removes and returns the item at index, if index is not provided, removes and returns the last item
    ls.index(x) returns the index of first x, if x is not in ls, ValueError
    ls.count(x) count the frequency of x
    ls.sort(key=None, reverse=False) key can be a lambda function, if multiple sorting rules, using tuple
    del ls[index] deletes one item in the list
    del ls delets the entire list

String

  • String is immutable

  • "" or str() is empty string

    Method Description
    str.capitalize() returns a string with first letter in upper case
    str.upper() returns a string with all characters in upper case
    str.lower() returns a string with all characters in lower case
    str.casefold() returns a string with all characters in lower case, it can work with more characters than lower method, use it for globalization or localization
    str.swapcase() returns a string with case swaped in str
    str.count(sub,start=None,end=None) returns the freq of a subtring, it can set starting index(inclusive) and ending index(exclusive)
    str.encode() returns an encoded version of string
    str.startswith(substr[, start, end]) returns True if str[start: end] starts with substr
    str.endswith(substr[, start, end]) returns True if str[start: end] ends with substr
    str.find(substr[, start, end]) returns the index of substr, returns -1 on failure, to find the last index of occurance, use str.rfind() instead
    str.index(substr[, start, end]) returns the index of substr, ValueError on failure, to find the last index of occcurance, use str.rindex() instead
    str.format(val1,...,valn) returns the formatted version of str: insert all values into placeholders in str, placeholders are represented using {}
    str.isalnum() returns True if all characters are alphanumeric
    str.isalpha() returns True if all characters are letters
    str.isnumeric() returns True if all characters are numeric values, "-1", "1.5" returns False for this method, because "-" and "." are not numeric
    str.isdigit() returns True if all characters are digits
    str.isdecimal() returns True if all characters are decimal numbers
    str.islower() returns True if all characters are in lower case, numbers, symbols and spaces are not checked, only alphabete characters
    str.isupper() returns True if all characters are in upper case, numbers, symbols and spaces are not checked, only alphabete characters
    str.isspace() returns True if all characters are white space
    str.join(s1,...,sn) returns a new string joined by n strings, str is the separator in between
    str.replace(s1, s2) returns a new string with all s1 in str replcaed by s2
    str.split(sep=, maxsplit=) returns a list of words separated by the delimiter with, if maxsplit = n, then there will be n + 1 segments
    str.strip(substr) returns a string with all leading and trailing characters in substr removed,to remove leading characters, use str.lstrip(substr), to remove trailing characters, use str.rstrip(substr)
    str.partition(substr) returns a tuple, (before substr, substr, after substr), search for first occurance of substr,to search for last occurance of substr, use str.rpartition(substr) instead, if substr is not in str, returns (str, "", "")
    str.zfill(len) returns a new string with 0 filled at the begining until the length is parameter len, if parameter len is smaller than len(str), simply returns str itself

Set

  • Contain unique and immutable objects

  • set() is empty set

    Method Description
    set(seq) create a set from a sequence
    s1 & s2, s1.intersection(s2) returns intersection set
    s1 | s2, s1.union(s2) returns union set
    s1 - s2, s1.difference(s2) returns difference set
    s1 ^ s2, s1.symmetric_difference(s2) returns symmetric difference set
    s1 > s2 returns True if s1 is a proper superset of s2
    s1 < s2 returns True if s1 is a proper subset of s2
    s1.issuperset(s2) returns True if s1 is a superset of s2
    s1.issubset(s2) returns True if s1 is a subset of s2
    s1.isdisjoint(s2) returns True is s1 & s2 is empty set
    s1.add(x) adds an item
    s1.remove(x) removes an item, if x not in the set, KeyError
    s1.discard(x) removes an item, if x not in the set, no Exception is raised
    s1.pop() removes a random item in the set
    s1.clear() removes all items in the set

Tuple

  • Tuple items are ordered, unchangable, and allow duplicate values

  • () or tuple() is empty tuple

    Method Description
    tup.count(val) returns the amount of occurance of val in tup, if val is not in tup, returns 0
    tup.index(val) returns the index of first val in tup, if val is not in tup, ValueError

Dictionary

  • {} or dict() is empty dictionary

    Method Description
    dt.keys() returns a view object containing all keys of dt in a list, type is dict_keys
    dt.values() returns a view object containing all values of dt in a list, type is dict_values
    dt.items() returns a view object containing all key-value pairs of dt in a list of tuples, type is dict_items
    dt.clear() clears all items in dt, None return type
    dt.copy() returns a deep copy of dt, modifying dt will not affect this copy
    dict.fromkeys(keys, value) returns a dictionary with a list of keys and a single value, value is optional, default value is None
    dt.get(key, value) returns dt[key], if key is not in dt, returns value, value is optional, default value is None
    dt.pop(key, value) removes a key-value pair from the dictionary, returns dt[key], value is optional, but if key is not in dt, and value is not provided, KeyError
    dt.popitem() removes the last item in dt, returns the item as key-value pair in a tuple
    dt.setdefault(key, value) if key in dt, returns dt[key], if key is not in dt, insert key in dt with value, value is optional, default value is None

Built-in

  • Category One

    Method Description
    int(x, base = n) returns an integer, if base is not provided, truncates numeric x to 0, if base is provided, x must be String
    long(x, base = n) returns a long integer, if base is not provided, truncates numeric x to 0, if base is provided, x must be String
    bin(x) returns a binary String of an integer x, the binary String has a format of 0bXX when positive, and -0bXX when negative
    oct(x) returns an octal String of an integer x, the octal String has a format of 0oXX when positive, and -0oXX when negative
    hex(x) returns a lowercase hexadecimal String of an integer x, the lowercase hexadecimal String has a format of 0xXX when positive, and -0xXX when negative
    ord(x) returns an integer representing the Unicode code point of a String x with length 1
    chr(i) returns a String of one character whose ASCII value is i, the inverse of ord
    str(obj) returns a string containing a nicely printable representation of obj
    bool([x]) returns Falses if x is not provided or x is zero-equivalent, returns True otherwise
    float([x]) returns a floating point number
    tuple([iterable]) returns a tuple whose order and item are the same as those in the iterable
    lsit([iterable]) returns a list whose order and item are the same as those in the iterable
    set([iterable]) returns a set whose items are taken from the iterable
    dict(mapping, **kwarg) returns a dictionary, mapping is key = value
  • Category Two

    Method Description
    pow(x, y[, z]) returns \(x^{y}\), if z is provided, returns efficiently \(x^{y} \mod z\)
    abs(x) returns the absolute value of x
    sum(iterable[, start]) sums start and the items of an iterable from left to right and returns the total
    max(iterable[, key]) returns the largest item in an iterable or the largest of two or more arguments, key is a function used when comparing items
    min(iterable[, key]) returns the smallest item in an iterable or the smallest of two or more arguments, key is a function used when comparing items
    round(num[,ndigits]) returns the floating number num rounded to ndigits digits after the decimal point
  • Category Three

    Method Description
    any(iterable) returns True if any element in the iterable is True. If the iterable is empty, returns False
    all(iterable) returns True if all elements in the iterable are True or if the iterable is empty
    filter(function, iterable) returns an iterator containing those elements of iterable for which function returns true, type is filter
    map(function, iterable) applies function to every item of iterable and returns an interator of the results, type is map
  • Category Four

    Method Description
    reversed(seq) returns a reverse iterator
    zip(*iterables, strict=False) iteratez over several iterables in parallel, producing tuples with an item from each one, returns an iterator of tuples
    eval(expression) evulates the String expression as a Python expression, returns the result

math

  • import math or from math import *

    Method Description
    math.ceil(x) returns the smallest integer grater than or equal to x
    math.floor(x) returns the largest integer smaller than or equal to x
    math.perm(n, k=None) requires Python >= 3.8, returns \(P^{k}_{n}\)/\(_nP_k\)
    math.comb(n,k=None) requires Python >= 3.8, returns \(C^{k}_{n}\)/\(_nC_k\)
    math.fabs(x) returns abs(x)
    math.factorial(n) returns factorial of n
    math.gcd(x, y) returns the greatest common divisior of x and y
    math.lcm(x, y) returns the least common multiplier of x and y
    math.exp(x) returns \(e^{x}\)
    math.log(x[, base]) returns \(log_{base}{x}\), base is optional, default base is \(e\)
    math.log2(x) returns \(log_{2}{x}\)
    math.log10(x) returns \(log_{10}{x}\)
    math.sqrt(x) returns \(\sqrt{x}\)
    math.sin(x), math.cos(x), math.tan(x) trigonometric functions
    math.pi \(PI\)
    math.e \(E\)
    math.inf it's equal to float('inf')
    math.nan \(NaN\)

collections

  • This module implements specialized container data types providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple

  • Counter

    Method Description
    Counter([iterable-or-mapping]) Returns a Counter is a dict subclass for counting hashable objects
    counter.most_common([n]) Returns a list, each item is a tuple of key and its associated count
    counter.total() Compute the sum of counts
  • deque

    Method Description
    deque([iterable[, maxlen]]) Returns a new deque object initialized left-to-right (using append()) with data from iterable. If iterable is not specified, the new deque is empty
    deque.append(x) Add x to the right side of the deque
    deque.appendleft(x) Add x to the left side of the deque
    deque.extend(iterable) Extend the right side of the deque by appending elements from the iterable argument
    deque.extendleft(iterable) Extend the left side of the deque by appending elements from iterable
    deque.count(x) Count the number of deque elements equal to x
    index(x[, start[, stop]]) Return the position of x in the deque (at or after index start and before index stop)
    insert(i, x) Insert x into the deque at position i, if the insertion would cause a bounded deque to grow beyond maxlen, IndexError
    pop() Remove and return an element from the right side of the deque, if deque is empty, IndexError
    popleft() Remove and return an element from the left side of the deque, if deque is empty, IndexError
    reverse() Reverse the elements of the deque in-place and then return None
    rotate(n=1) Rotate the deque n steps to the right. If n is negative, rotate to the left, deque.rotate(n=1) is just deque.appendleft(deque.pop()), and deque.rotate(n=-1) is jsut deque.append(deque.popleft())
    field: deque.maxlen Maximum size of a deque or None if unbounded
  • defaultdict

    Method Description
    defaultdict(default_factory=None, /[, ...]) Return a new dictionary-like object

functools

  • import functools or from functools import *

    Method Description
    @cache Create a thin wrapper around a dictionary lookup for the function arguments, faster than @lru_cache
    @lru_cache(maxsize=N) Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments
    reduce(function, iterable[, initializer]) Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value

heapq

  • import heapq or from heapq import *

  • Python implements a min heapq with index starting from 0, \(\forall k > 0\), \(heap[k] \leq heap[2 * k + 1]\) and \(heap[k] \leq heap[2 * k + 2]\), the smallest one in the heap is \(heap[0]\)

    Method Description
    heapify(x) Transform list x into a heap, in-place, linear time
    heappush(heap, item) Push the value onto the heap, maintaining the heap invariant
    heappop(heap) Pop and return the smallest item from the heap, maintaining the heap invariant. If the heap is empty, IndexError is raised.To access the smallest item without popping it, use heap[0]
    heappushpop(heap, item) Push item on the heap, then pop and return the smallest item from the heap, this method is more efficient than manually run heappush(heap, item) and then heappop(heap)

Java

Array

  • Fixed length, single type linear structure

  • import java.util.Arrays;

    Method/Field Description
    field:arr.length Return the length of the array
    Arrays.asList(arr) Returns a fixed-size list backed by the specified array
    Arrays.binarySearch​(T[] a, T key) Searches the specified array of T for the specified value using the binary search algorithm
    Arrays.binarySearch​(T[] a, int fromIndex, int toIndex, T key) Searches a range of the specified array of T for the specified value using the binary search algorithm
    Arrays.compare​(T[] a, T[] b) Compares two T arrays lexicographically
    Arrays.compare​(T[] a, int aFromIndex, int aToIndex, T[] b, int bFromIndex, int bToIndex) Compares two T arrays lexicographically over the specified ranges
    Arrays.copyOf​(T[] original, int newLength) Copies the specified array, truncating or padding with type T zero-equivalents so the copy has the specified length
    Arrays.copyOfRange​(T[] original, int from, int to) Copies the specified range of the specified array into a new array
    Arrays.equals​(T[] a, T[] a2) Returns true if the two specified arrays of T are equal to one another
    Arrays.fill(T[] a, T val) Assigns the specified T value to each element of the specified array of T
    Arrays.fill​(T[] a, int fromIndex, int toIndex, T val) Assigns the specified T value to each element of the specified range of the specified array of T
    Arrays.sort(T[] a) Sorts the specified array of objects into ascending order, according to the natural ordering of its elements
    Arrays.toString(T[] a) Returns a string representation of the contents of the specified array

String Class

  • String is immutable in Java

    Method/Field Description
    String(T[] arr) Construct a new string for an array
    str.charAt(int index) Returns the char value at the specified index
    str.endsWith(String suffix) Tests if this string ends with the specified suffix
    str.startsWith​(String prefix) Tests if this string starts with the specified prefix
    str.trim() Returns a string with all leading and trailing space removed
    str.strip() Returns a string with all leading and trailing space removed
    str.stripLeading() Returns a string with all leading white space removed.
    str.stripTrailing() Returns a string with all trailing white space removed
    str.indexOf(int n) Returns the index within this string of the first occurrence of the specified character
    str.lastIndexOf(int ch) Returns the index within this string of the last occurrence of the specified character
    str.length() Returns the length of this string
    str.toCharArray() Converts this string to a new character array
    str.toLowerCase() Converts all of the characters in this String to lower case using the rules of the default locale
    str.toUpperCase() Converts all of the characters in this String to upper case using the rules of the given Locale
    str.toString() This object which is already a string
    str.valueOf(T a) Returns the string representation of the T element
    str.valueOf(char[] c) Returns the string representation of the char array argument

List interface

  • List interface
    • import java.util.List;

    • List<E> list = new ArrayList<>();, List<E> list = new LinkedList<>();

    • List interface extends Collection interface, Collection interface extends Iterable interface, so you can use forEach loop and iterator on the list

      Method Description
      public boolean add(E e) Appends the specified element to the end of this list, returns true if the list is changed
      public void add(int index, E e) Inserts the specified element at the specified position in this list
      public boolean addAll(Collection<? extends E> c) Appends all of the elements in the specified collection to the end of this list, returns true if the list is changed
      public boolean addAll(int index, Collection<? extends E> c) Inserts all of the elements in the specified collection into this list, starting at the specified position, returns true if the list is changed
      public void clear() Removes all of the elements from this list
      public boolean contains(Object o) Returns true if this list contains the specified element
      public int indexOf(Object o) Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element
      public int lastIndexOf(Object o) Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element
      public E get(int index) Returns the element at the specified position in this list
      public E set(int index, E element) Replaces the element at the specified position in this list with the specified element, returns replaced value
      public E remove(int index) Removes the element at the specified position in this list
      public boolean remove(Object o) Removes the first occurrence of the specified element from this list, returns true if the object is in the list
      public boolean removeAll(Collection<?> c) Removes from this list all of its elements that are contained in the specified collection, returns true if the list is changed
      public boolean retainAll(Collection<?> c) Retains only the elements in this list that are contained in the specified collection, returns true if the list is changed
      size() Returns the number of elements in this list
      public List<E> subList​(int fromIndex, int toIndex) Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive
      public boolean isEmpty() Returns true if the list is empty
      public int size() Returns the amount of elements in the list
      public Iterator<E> iterator() Returns an iterator over the elements in this list in proper sequence
      public Object[] toArray() Returns an array containing all of the elements in this list in proper sequence
      public T[] toArray(T[] a) Returns an array containing all of the elements in this list in proper sequence, the runtime type of the returned array is that of the specified array. Exp: Integer[] res = list.toArray(new Integer[0]);
  • ArrayList
    • import java.util.ArrayList;
    • List<E> list = new ArrayList<>();
    • Resizable-array implementation of the List interface
    • Permits all types of elements, including null
    • The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time. All of the other operations run roughly in linear time
    • The iterators on ArrayList are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException
  • LinkedList
    • import java.util.LinkedList;
    • List<E> list = new LinkedList<>();
    • Doubly-linked list implementation of the List interface
    • Permits all types of elements, including null
    • The add, remove, get, set, iterator operations run in constant time
    • The iterators on LinkedList are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException

Set interface

  • Set interface
    • import java.util.Set;

    • Set<E> set = new HashSet<>();, Set<E> set = new TreeSet<>();

    • Set interface extends Collection interface, Collection interface extends Iterable interface, so you can use forEach loop and iterator on the list

      Method Description
      public boolean add(E e) Adds the specified element to the set if it is not already present, returns true if the set is changed
      public boolean addAll(Collection<? extends E> c) Adds all of the elements in the specified collection to the set if they're not already present, returns true if the set is changed
      public void clear() Removes all of the elements from this set
      public boolean contains(Object o) Returns true if this set contains the specified element
      public boolean containsAll​(Collection<?> c) Returns true if this set contains all of the elements of the specified collection
      public boolean remove(Object o) Removes the specified element from this set if it is present, returns true if the set is changed
      public boolean removeAll(Collection<?> c) Removes from this set all of its elements that are contained in the specified collection, returns true if the set is changed
      public boolean retainAll(Collection<?> c) Retains only the elements in this set that are contained in the specified collection, returns true if the set is changed
      size() Returns the number of elements in this set
      public boolean isEmpty() Returns true if the list is empty
      public int size() Returns the amount of elements in the list
      public Iterator<E> iterator() Returns an iterator over the elements in this list in proper sequence
      public Object[] toArray() Returns an array containing all of the elements in this set
      public T[] toArray(T[] a) Returns an array containing all of the elements in this set, the runtime type of the returned array is that of the specified array. Exp: Integer[] res = set.toArray(new Integer[0]);
  • HashSet
    • import java.util.HashSet;
    • Set<E> set = new HashSet<>();
    • This class implements the Set interface, backed by a HashMap instance
    • This class permits null elements, elements are unordered
    • This class offers constant time performance for basic operations(add, remove, contains, size, isEmpty), iterating over the set requires linear time
    • Iterators on HashSet are fail-fast
  • TreeSet
    • import java.util.TreeSet;
    • Set<E> set = new TreeSet<>();
    • This class implements the Set interface, backed by a TreeMap instance
    • This class does not permits null elements, elements are ordered using their natural ordering, or by a Comparator provided at set creation time
    • This class provides guaranteed \(log(n)\) performance for basic operations(add, remove, contains,size, isEmpty)
    • Iterators on TreeSet are fail-fast

Map interface

  • Map interface
    • import java.util.Map;

    • Map<K, V> map = new HashMap<>();, Map<K, V> map = new TreeMap<>();

    • Map interface does not extend Iterable interface, so you cannot use forEach loop or iterator on a map itself, but it provides three collection views: keySet, values, and entrySet, which are all collections of the corresponding type

    • Inner interface: Map.Entry, entry.getKey() and entry.getValue()

      Method Description
      public void clear() Removes all of the mappings from this map
      public boolean containsKey​(Object key) Returns true if this map contains a mapping for the specified key
      public boolean containsValue​(Object value) Returns true if this map contains a mapping for the specified value
      public Set<Map.Entry<K, V>> entrySet() Returns a Set view of the mappings contained in this map
      public V get(Object key) Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key
      public V getOrDefault(Object key, V defaultValue) Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key
      public boolean isEmpty() Returns true if this map contains no key-value mappings
      public Set<K> keySet() Returns a Set view of the keys contained in this map
      public void put(K key, V value) Associates the specified value with the specified key in this map
      public V putIfAbsent​(K key, V value) If the specified key is not already associated with a value, associates it with the given value and returns null, else returns the current value
      public void remove(Object key) Removes the mapping for a key from this map if it is present
      public boolean remove(Object key, Object value) Removes the entry for the specified key only if it is currently mapped to the specified value, returns true if the map is changed
      public int size() Returns the number of key-value mappings in this map
      public Collection<V> values() Returns a Collection view of the values contained in this map
  • HashMap
    • java.util.HashMap;
    • Map<K, V> map = new HashMap<>();
    • Hash table based implementation of the Map interface
    • It permits one null key and multiple null values, elements are unordered
    • This class provides constant-time performance for the basic operations (get and put, containsKey, containsValue, size, isEmpty), iterating over the map requires linear performance
    • Iterators on HashMap are fail-fast
  • TreeMap
    • import java.util.TreeMap;
    • Map<K, V> map = new TreeMap<>();
    • A Red-Black tree based implementation of the NavigableMap interface, the NavigableMap interface extends the Map interface
    • It does not permit null key, but it does permit multiple null values, elements are ordered using their natural ordering, or by a Comparator provided at map creation time
    • This class provides guaranteed \(log(n)\) time cost for the containsKey, get, put and remove operations

Math class

  • java.lang.Math, so you do not need to import anything

    Method Description
    public static double E \(E\)
    public static double PI \(PI\)
    public static abs(T a) Returns the absolute value of a T value, T can be double, float, int, long
    public static double acos(double a), public static double asin(double a), public static double atan(double a) arc trigonometric functions
    public static double cos(double a), public static double sin(double a), public static double tan(double a) trigonometric functions
    public static double cosh(double a), public static double sinh(double a), public static double tanh(double a) hyperbolic trigonometric functions
    public static double ceil(double a) Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer
    public static double floor(double a) Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer
    public static double exp(double a) Returns e raised to the power of a double value
    public static double log(double a) Returns the natural logarithm of a double value
    public static T max(T a, T b) Returns the greater of two double values, T can be double, float, int, long
    public static T min(T a, T b) Returns the smaller of two double values, T can be double, float, int, long
    public static double random() Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0
    public double sqrt(double a) Returns the correctly rounded positive square root of a double value

Collections class

  • import java.util.Collections;

    Method Description
    public static <T> int binarySearch​(List<? extends Comparable<? super T>> list, T key) Searches the specified list for the specified object using the binary search algorithm, returns the index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1)
    public static <T> void copy​(List<? super T> dest, List<? extends T> src) Copies all of the elements from one list into another
    pub static <T> void fill​(List<? super T> list, T obj) Replaces all of the elements of the specified list with the specified element
    public static <T extends Object & Comparable<? super T>> T max​(Collection<? extends T> coll) Returns the maximum element of the given collection, according to the natural ordering of its elements
    public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) Returns the minimum element of the given collection, according to the natural ordering of its elements
    public static void reverse​(List<?> list) Reverses the order of the elements in the specified list
    public static <T extends Comparable<? super T>> void sort​(List<T> list) Sorts the specified list into ascending order, according to the natural ordering of its elements
    public static void swap​(List<?> list, int i, int j) Swaps the elements at the specified positions in the specified list

Stack class

  • import java.util.Stack;

  • Stack<E> stack = new Stack<>();

  • This class represents a LIFO stack of objects

  • This class extends Vector class and implements the List interface

  • A more complete and consistent set of LIFO stack operations are provided by the Deque interface, which should be used in preference to this class, Deque<Integer> stack = new ArrayDeque<>();

    Method Description
    public boolean empty() Tests if this stack is empty
    public E peek() Looks at the object at the top of this stack without removing it from the stack
    public E pop() Removes the object at the top of this stack and returns that object as the value of this function
    public E push(E item) Pushes an item onto the top of this stack
    public int search(Object o) Returns the 1-based position where an object is on this stack

Queue interface

  • import java.util.Queue

  • Queue<E> queue = new ArrayDeque<>();, Queue<E> queue = new LinkedList<>();

  • Queues typically, but do not necessarily, order elements in a FIFO manner

    Method Description
    public boolean add(E e) Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available
    public E element() Retrieves, but does not remove, the head of this queue
    public boolean offer(E e) Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions
    public E peek() Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty
    public E poll() Retrieves and removes the head of this queue, or returns null if this queue is empty
    public E remove() Retrieves and removes the head of this queue
  • Deque interface

    • import java.util.Deque;

    • Deque<E> deque = new ArrayDeque<>();, Deque<E> deque = new LinkedList<>();

    • A linear collection that supports insertion and removal at both ends. The name deque is short for "double ended queue" and is usually pronounced "deck"

    • Summary of Deque methods

      First element(Head)

      Last element(Tail)

      Throws exception

      Special value

      Throws exception

      Special value

      Insert

      addFirst(e)

      offerFirst(e)

      addLast(e)

      offerLast(e)

      Remove

      removeFirst(e)

      pollFirst(e)

      removeLast(e)

      pollLast(e)

      Examine

      getFirst(e)

      peekFirst(e)

      getLast(e)

      peekLast(e)

    • Comparison of Queue and Deque methods

      Queue Method Equivalent Deque Method
      add(e) addLast(e)
      offer(e) offerLast(e)
      remove() removeFirst()
      poll() pollFirst()
      element() getFirst()
      peek() peekFirst()
    • Comparison of Stack and Deque methods

      Queue Method Equivalent Deque Method
      push(e) addFirst(e)
      pop() removeFirst()
      peek() getFirst()
    • Deque methods

      Method Description
      public boolean add(E e) Inserts the specified element at the end of this deque, returns true if there is enough space, otherwise throws IllegalStateException
      public void addFirst(E e) Inserts the specified element at the front of the deque, returns true if there is enough space, otherwise throws IllegalStateException
      public void addLast(E e) Inserts the specified element at the end of the deque, returns true if there is enough space, otherwise throws IllegalStateException
      public boolean contains(Object o) Returns true if this deque contains the specified element
      public E element() Retrieves, but does not remove, the first element of this deque
      public E getFirst() Retrieves, but does not remove, the first element of this deque
      public E getLast() Retrieves, but does not remove, the last element of this deque
      public boolean offer(E e) Inserts the specified element at the end of this deque, returns true if there is enough space, otherwise false
      public boolean offerFirst(E e) Inserts the specified element at the front of this deque unless it would violate capacity restrictions
      public boolean offer(E e) Inserts the specified element at the end of this deque unless it would violate capacity restrictions
      public E peek() Retrieves, but does not remove, the first element of this deque, or returns null if the deque is empty
      public E peekFirst() Retrieves, but does not remove, the first element of this deque, or returns null if the deque is empty
      public E peekLast() Retrieves, but does not remove, the last element of this deque, or returns null if the deque is empty
      public E poll() Retrieves and removes the first element of this deque, or returns null if this deque is empty
      public E pollFirst() Retrieves and removes the first element of this deque, or returns null if this deque is empty
      public E pollLast() Retrieves and removes the last element of this deque, or returns null if this deque is empty
      public E remove() Retrieves and removes the first element of this deque
      public E remove(Object o) Removes the first occurrence of the specified element from this deque
      public E removeFirst() Retrieves and removes the first element of this deque
      public E removeLast() Retrieves and removes the last element of this deque
      public int size() Returns the number of elements in the deque
      public boolean isEmpty() Returns whether there are 0 elements in the deque
  • PriorityQueue class

    • import java.util.PriorityQueue;

    • PriorityQueue<E> pq = new PriorityQueue<>();

    • PriorityQueue with customized comparator

      1
      2
      3
      4
      5
      6
      PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>(){
      @override
      public int compare(Integer a, Integer b) {
      return func(a, b); // func(a, b) < 0, then a is closer to the head of the queue
      }
      })

    • An unbounded priority queue based on a priority heap

    • Does not permit null elements, elements are ordered using their natural ordering or by a Comparator provided at queue construction time, depending on which constructor is used

    • The head of a priority queue is the least element with respect to the specified ordering

    • This class provides \(O(log(n))\) time for the enqueuing and dequeuing methods (offer, poll, remove and add); linear time for the remove(Object) and contains(Object) methods; and constant time for the retrieval methods (peek, element, and size)

      Method Description
      public boolean add(E e) Inserts the specified element into this priority queue
      public void clear() Removes all of the elements from this priority queue
      public boolean contains(Object o) Returns true if this queue contains the specified element
      public boolean offer(E e) Inserts the specified element into this priority queue, returns true if the priority queue is changed
      public boolean remove(Object o) Removes a single instance of the specified element from this queue, if it is present, returns true if the priority queue is changed
      public boolean removeAll​(Collection<?> c) Removes all of this collection's elements that are also contained in the specified collection, returns true if the priority queue is changed
      public boolean retainAll(Collection<?> c) Retains only the elements in this collection that are contained in the specified collection, returns true if the priority queue is changed
      public Object[] toArray() Returns an array containing all of the elements in this queue
      public T[] toArray(T[] a) Returns an array containing all of the elements in this queue; the runtime type of the returned array is that of the specified array