Tool Class
java.lang, automatically importedjava.utiljava.iojava.awt,javax.swing, GUIjava.netjava.sql
JDK API DOC
Object class
equals()==is reference equalequals()is content;one.equals(another)- If override
equals(), need to overridehashCode()
getClass()- a
finalmethod, cannot be overloaded
- a
toString()return a string of the objectfinalize()- thread:
notify(),notifyAll(),wait()
Wrapper
Wrapper for primitive data type to ref type, like Integer
- Constant:
Integer.MAX_VALUE,Double.NaN,Double.POSITIVE_INFINITY valueOf(String),toString()- convert
- get value:
xxxxValue()intValue()forInteger
- value is immutable
- Override
toString(),equals() Double:parseDouble(),max,min…
Boxing and Unboxing
Integer I = 5;I = Integer.valueOf(5);
int i = I;i = I.intValue();
Math
EPIabs()floor()exp()remainder(double f1, double f2)log()min(float a, float b)random(): 0 - 1rint(): 4.4 to 4; 4.51 to 5sqrt()sin(),cos(),tan(),asin(),acon(),atan()
System
System.getProperty(String name)System.getProperties()- add property while running
java -D varName = varValue MyProg
String
Stringclass is immutableStringBuffer,StringBuildercan be mutable
Ops:
- Return a new instance:
concat,replace,replaceAll,substring,toLowerCase,toUpperCase,trim,toString - Search:
endsWith,startsWith,indexOf,lastIndexOf - Compare:
equals,equalsIgnoreCase charAt(pos),length- format:
%1$,8.5f%No$sign...
StringBuffer
Constructor
- StringBuffer()
- StringBuffer(int capacity)
- StringBuffer(String initialString)
Methods
- append
- insert
- reverse
- setCharAt
- setLength
String split
java.util.StringTokenizer- Constructor:
StringTokenizer(String str, String delim);
Method:
public int countTokens(): no. of splitspublic boolean hasMoreTokens()public String nextToken()
Date
- Calendar
- get an instance:
Calendar.getInstance() get(DAY_OF_MONTH),.getDisplayName(DAY_OF_WEEK).set,.add(HOUR,1),.roll(MONTH,5).setTime(date),.getTime()- use fields and methods directly:
import static java.util.Calendar.*;
- get an instance:
- Date
new Date(),new Date(System.currentTimeMillis()).setTime(long),.getTime()
SimpleDateFormat("yyyy-MM-ddHH:mm:ss").format,.parse
Time
java.time.*java.time.format.*
Class:
- Instant
- Clock
- Duration
- LocalDateTime
- LocalDate
- LocalTime
.of,.parse,.format,.plus,.minus
Collection API
3 interface, w sub interfaces:
- Collection
- List: remember order, allow duplicates
- Set: no order, not allow duplicates
- Map
- key-value pair
Methods:
add(element : Object): booleanremove(element : Object): booleansize(): intisEmpty(): booleancontains(element : Object): booleaniterator(): Iterator
Structure:
- Collection
- Set
- HashSet
- TreeSet
- List
- Vector
- Stack
- ArrayList
- LinkedList
- Vector
- Queue
- LinkedList
- PriorityQueue
- ArrayQueue
- Set
List
Linear list: List<Type> name = new LinkedList<>();
Class:
- ArrayList
- LinkedList
Interface:
public interface List<E> extends Collection<E> {
E get(int index);
E set(int index, E element);
void add(int index, E element);
E remove(int index);
int indexOf(Object o);
}
Iterator
All Collection can generate.
Iterator iterator= iterable.iterator();while( iterator.hasNext()) doSomething( iterator.next());- equivalent to enhanced for
Stack
- LIFO
public Object push(Object item)public Object pop()public boolean empty()Stack<Type> name = new Stack<>();
Queue
- FIFO
- LinkedList
- Insert:
add(e),offer(e)return value - Remove:
remove(),poll()return value - Examine:
element(),peek()return value
Set
HashSetTreeSet
No duplicates
hashCode()not the same- If same, use
==andequals()having unequal results
Map
Can get sets:
entrySet()keySet()values()
Realization:
- HashMap
- TreeMap
Ops:
Map<String,String> map = new TreeMap<String,String>();.put(key, value).get(key)entry.getKey()entry.getValue().keySet().entrySet().iterator()
Sort
- Arrays class can be used to sort and search array
Arrays.asList(10, 7, 6, 5, 9)return a list objectsort(),binarySearch(); dosort()first beforebinarySearch()Arrays.<String>sort(s);
- Collection
Colletions.sort( school, new ComparatorName())- or
Colletions.sort( school, (p1,p2)-> p1.age-p2.age)
Generic
Must be ref type
Class
import java.util.*;
class GenericTreeClass {
public static void main(String[] args){
TNode<String> t = new TNode<>("Roo");
t.add("Left"); t.add("Middle"); t.add("Right");
t.getChild(0).add("aaa");
t.getChild(0).add("bbb");
t.traverse();
}
}
class TNode<T>
{
private T value;
private ArrayList<TNode<T>> children = new ArrayList<>();
TNode(T v) { this.value = v; }
public T getValue() { return this.value; }
public void add(T v) {
TNode<T> child = new TNode<>(v);
this.children.add(child);
}
public TNode<T> getChild(int i) {
if ((i < 0) || (i > this.children.size())) return null;
return (TNode<T>)this.children.get(i);
}
public void traverse() {
System.out.println(this.value);
for (TNode child : this.children)
child.traverse();
}
}
Method
import java.util.*;
class GenericMethod {
public static void main(String[] args){
Date date = BeanUtil.<Date>getInstance("java.util.Date");
System.out.println(date);
}
}
class BeanUtil{
public static <T> T getInstance( String clzName ){
try
{
Class c = Class.forName(clzName);
return (T) c.newInstance();
}
catch (ClassNotFoundException ex){}
catch (InstantiationException ex){}
catch (IllegalAccessException ex){}
return null;
}
}
Limit on type
- ?: all:
reverse(List<?> list) - extends:
addAll(Collection<? extends E> col) - super:
fill(List<? super T> list, T obj), fruit for the list, can have apple.. in it
Popular algorithms
Exhaust algo, brute force
for(;;){ if(); }
Iterative algo
while() { x = f(x); }
Recursive algo
f(n){f(n-1);}
Back-track
x++; if(...) x--;
