Mapa mental
XSPELSODE
Conteúdo do mapa
XSPELSODE
Class
- Class Member
- Instance variables
- State
- Lives on the heap
- reference variable
- Default value: 0, 0.0, false, '\u0000', null
- non-access modifiers
- transient
- volatile
- final
- method
- Local variable
- Lives on the stack
- final => constant
- No default value; using uninitialized one gives compiler error
- Behavior
- Arguments vs Parameters
- Var-arg type
- Return Type
- Covariant Returns
- non-access modifiers
- Final Method
- Abstract Method
- Synchronized Method
- Native Method
- Strictfp Method
- Local variable
- Instance variables
- static varibales & static methods
- Inheritance
- Overloading
- MUST change the argument list
- CAN change the return type
- CAN change the access modifier
- CAN declare new or broader checked exceptions
- CAN coexists in the same class or in a subclass
- Overriding
- MUST not change the argument list
- CAN not change the return type except for covariant returns
- Must not throw new or broader checked exceptions
- Can reduce or eliminate exceptions
- Must not make more restrictive
- CAN be less restrictive
- when an exact match isn't found, the compiler determines which method to use
- widening has precedence over autoboxing) (for backward compatibility)
- autoboxing has precedence over Var-args
- the JVM uses the method with the smallest argument that is wider than the parameter
- Widening
- Widening Reference Variable
- autobox and then widen the parameter for a match to be made is LEGAL: Case a parameter of type Object
- Widening Primitive Variable
- widen and then autobox the parameter for a match to be made is ILLEGAL : too much for the compiler
- Widening Reference Variable
- You can combine var-args with either widening or boxing.
- Abstract Class
- super keyword
- instanceof
- Overloading
- Constructor
- Instantiation
- Constructor Chaining
- can use any access modifier, including private
- The constructor name must match the name of the class.
- must not have a return type
- legal (but stupid) to have a method with the same name as the class
- Abstract classes have constructors
- Interfaces do not have constructors (not part of an object's inheritance tree)
- The only way a constructor can be explicitely invoked is from within another constructor
- Default constructor
- Default no-arg constuctor automatically generated by the compiler: If you don't type a constructor into your class code
- A no-arg constructor is not necessarily the default
- the default constructor is always a no-arg constructor
- The default constructor has the same access modifier as the class, has no arguments, includes a no-arg call to the super constructor (super()).
- super constructor
- Every constructor has, as its first statement, either a call to an overloaded constructor (this()) or a call to the superclass constructor (super()), although remember that this call can be inserted by the compiler.
- If you do not type in the call to super() or a call to this(), the compiler will insert a no-arg call to super() for you, as the very first statement in the constructor
- A call to super() can be either a no-arg call or can include arguments passed to the super constructor.
- Only static variables and methods can be accessed as part of the call to super() or this(): super(Animal.NAME)
- The first line in a constructor must be a call to super() or a call to this().
- object
- equals(), hashCode(), and toString()
- overriding equals() & hashCode()
- use the instanceof operator to be sure you're evaluating an appropriate class.
- compare the objects' significant attributes
- the equals() contract
- Reflexive: x.equals(x) is true.
- Symmetric: If x.equals(y) is true, then y.equals(x) must be true.
- Transitive: If x.equals(y) is true, and y.equals(z) is true, then z.equals(x) is true.
- Consistent: Multiple calls to x.equals(y) will return the same result.
- Null: If x is not null, then x.equals(null) is false.
- If you override equals(), override hashCode().
- An overridden equals() must be at least as precise as its hashCode() mate.
- if two objects are equal, their hashcodes must be equal.
- hashCode() contract
- Consistent: multiple calls to x.hashCode() return the same integer.
- If x.equals(y) is true, x.hashCode() == y.hashCode() is true.
- If x.equals(y) is false, then x.hashCode() == y.hashCode() can be either true or false, but false will tend to create better efficiency.
- transient variables aren't appropriate for equals() and hashCode().
- overriding equals() & hashCode()
- Lives on the heap
- State + Behavior
- equals(), hashCode(), and toString()
- Initialization Block
- static { x = 7 ; } // static init block
- { y = 8; } // instance init block
- Init blocks execute in the order they appear.
- Static init blocks run once, when the class is first loaded.
- Instance init blocks run every time a class instance is created.
- Instance init blocks run after the constructor's call to super().
- IS-A vs HAS-A
- Polymorphism
- Encapsulation
- Class Member
variables
- Primitives variables
- Primitive Casting
- Boxing, Autoboxing Unboxing, Auto-unboxing
- Wrapper Classes
- Boolean, Byte, Character, Short, Integer, Long, Float, Double
- new Wrapper(primitif type) or new Wrapper(String) except new Character(char)
- new Float(double) possible
- static Wrapper.valueOf(String value[, int radix]):wrapper
- NumberFormatException
- static Wrapper.parseXxx(String value[, int radix]):primitive value
- static Wrapper.toXxxString(int or long) (Binary, Hexadecimal, Octal):String
- Wrapper Conversion Utilities wrapper.xxxValue():primitive value
- ==, ++, -- involve auto-unboxing auto-boxing
- != coparaison does not involve auto-unboxing auto-boxing
- if(Boolean b) unbox
- NullPointerException
- Wrapper Classes
- boolean, byte, char, short, int, long, float, double
- size matters
- Reference variables
- Reference Casting
- type matters
- Scope
- Static variables: have the longest scope, they are created when the class is loaded, and they survive as long as the class stays loaded in the Java Virtual Machine (JVM)
- Instance variables: created when a new instance is created, and they live until the instance is removed
- Local variables: live as long as their method remains on the stack
- liBlock variables: ve only as long as the code block is executing
- Primitives variables
Literal Values
- Integer Literals
- Decimal Literals
- Octal Literals: 06
- Hexadecimal Literals: 0xFFFFl
- Floating-Point Literals: 11301874.9881024
- Boolean Literals: true, false
- Character Literals: 'a', '\u004E'
- String Literals: "Word"
Interface
- Constants
- Implementation
Arrays & Collections & Maps
- Array
- instanceof Object
- attribute length not method
- Lists and Sets have a toArray() method to create arrays.
- Iterable<T>
- Collection<E>
- Common collection activities
- adding objects
- removing objects
- verifying object inclusion
- retrieving objects
- iterating
- List<E>
- Ordered with an index
- boolean addAll(int index, Collection<? extends E> c) void add(int index, E element)
- int [last]IndexOf(Object o) E get(int index)
- E set(int index, E element) E remove(int index)
- List<E> subList(int fromIndex, int toIndex) ListIterator<E> listIterator([int index])
- Permit null
- Duplicates allowed
- ArrayList: Fast iteration, Fast random access
- new ArrayList([Collection<? extends E> c])
- new ArrayList(int initialCapacity)
- Vector: same as ArrayList except has synchronized methods (Slower ArrayList)
- new Vector([Collection<? extends E> c])
- new Vector(int initialCapacity[, int capacityIncrement])
- LinkedList: Good for adding elements to the ends
- new LinkedList([Collection<? extends E> c])
- Set<E>
- May or may not be ordered and/or sorted
- Duplicates not allowed
- SortedSet<E>
- E first() E last()
- SortedSet<E> subSet(E fromElement, E toElement) SortedSet<E> headSet(E toElement) SortedSet<E> tailSet(E fromElement)
- NavigableSet<E>
- E ceiling(E e) E floor(E e) _ E higher(E e) E lower(E e) E pollFirst() _ E pollLast()
- NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) NavigableSet<E> headSet(E toElement, boolean inclusive) NavigableSet<E> tailSet(E fromElement, boolean inclusive) NavigableSet<E> descendingSet()
- Iterator<E> descendingIterator()
- TreeSet<E>: Sorted order, Null not allowed
- new TreeSet([Collection<? extends E> c])
- new TreeSet(Comparator<? super E> comparator)
- new TreeSet(SortedSet<E> s)
- Permit at most one null
- HashSet<E>: Fast access, No ordering, Fast access
- new HashSet([Collection<? extends E> c])
- new HashSet(int initialCapacity[, float loadFactor])
- LinkedHashSet<E>: Insertion order, Fast access
- new LinkedHashSet([Collection<? extends E> c])
- new LinkedHashSet(int initialCapacity[, float loadFactor])
- boolean addAll(Collection<? extends E> c) boolean add(E e)
- boolean containsAll(Collection<?> c) boolean contains(Object o)
- boolean removeAll(Collection<?> c) boolean remove(Object o)
- boolean retainAll(Collection<?> c)
- Object[] toArray() boolean isEmpty() void clear() int size()
- Common collection activities
- Iterator<T> iterator()
- Map<K,V>
- void putAll(Map<? extends K,? extends V> m)
- V put(K key, V value) V get(Object key) V remove(Object key)
- boolean containsValue(Object value) boolean containsKey(Object key)
- Set<Map.Entry<K,V>> entrySet() Collection<V> values() Set<K> keySet()
- boolean isEmpty() int size() void clear()
- SortedMap<K,V>
- Comparator<? super K> comparator()
- K firstKey() K lastKey()
- SortedMap<K,V> subMap(K fromKey, K toKey) SortedMap<K,V> headMap(K toKey) SortedMap<K,V> tailMap(K fromKey)
- NavigableMap<K,V>
- Map.Entry<K,V> ceilingEntry(K key) Map.Entry<K,V> floorEntry(K key)
- Map.Entry<K,V> firstEntry() Map.Entry<K,V> lastEntry()
- Map.Entry<K,V> higherEntry(K key) Map.Entry<K,V> lowerEntry(K key)
- Map.Entry<K,V> pollFirstEntry() Map.Entry<K,V> pollLastEntry()
- K ceilingKey(K key) K floorKey(K key)
- K higherKey(K key) K lowerKey(K key)
- NavigableMap<K,V> headMap(K toKey, boolean inclusive) NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) NavigableMap<K,V> descendingMap()
- NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)
- TreeMap<K,V>: A sorted map, + null keys are not allowed
- new TreeMap([Map<? extends K,? extends V> m])
- new TreeMap(SortedMap<K,? extends V> m)
- TreeMap(Comparator<? super K> comparator)
- HashMap<K,V>: Fastest updates (key/values) & access, Allows one null key, many null values, No order
- new HashMap([Map<? extends K,? extends V> m])
- new HashMap(int initialCapacity[, float loadFactor])
- LinkedHashMap<K,V>: Faster iterations & access, terates by insertion order or last accessed, Allows one null key, many null values
- new LinkedHashMap([Map<? extends K,? extends V> m])
- new LinkedHashMap(int initialCapacity[, float loadFactor[, boolean accessOrder]])
- Hashtable<K,V>: same as HashMap except has synchronized methods (Slower HashMap) + null values and null keys are not allowed
- new Hashtable([Map<? extends K,? extends V> t])
- new Hashtable(int initialCapacity[, float loadFactor])
- May or may not be ordered and/or sorted
- Duplicate keys are not allowed
- Collection<E>
- java.util.Collections t holds static collection utility methods
- final Set EMPTY_SET
- final List EMPTY_LIST
- final Map EMPTY_MAP
- <T extends Comparable<? super T>> void sort(List<T> list)
- <T> void sort(List<T> list, Comparator<? super T> c)
- void reverse(List<?> list)
- void swap(List<?> list, int i, int j)
- <T> void copy(List<? super T> dest, List<? extends T> src)
- <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll)
- <T extends Object & Comparable<? super T>> T (min|max)(Collection<? extends T> coll)
- <T> T (min|max)(Collection<? extends T> coll, Comparator<? super T> comp)
- void rotate(List<?> list, int distance)
- <T> boolean replaceAll(List<T> list, T oldVal, T newVal)
- int frequency(Collection<?> c, Object o)
- boolean disjoint(Collection<?> c1, Collection<?> c2)
- <T> boolean addAll(Collection<? super T> c, T... elements)
- <T> (Collection|List|Set|SortedSet|Map)<T> unmodifiable(Collection|List|Set|SortedSet|Map)((Collection|List|Set|SortedSet|Map)<? extends T> c)
- <T> Comparator<T> reverseOrder()
- Four basic sub-flavors of collections: Sorted, Unsorted, Ordered, Unordered
- Sorting can be alphabetic, numeric, or programmer-defined
- Four basic flavors of collections: Lists, Sets, Maps, Queues
- Collections hold only Objects, but primitives can be autoboxed.
- Iterate with the enhanced for, or with an Iterator via hasNext() & next()
- java.util.Arrays: staticmethods for manipulating arrays
- void sort((int|long|short|char|byte|float|double)[] a[, int fromIndex, int toIndex])
- <T> void sort(T[] a, [int fromIndex, int toIndex,] Comparator<? super T> c)
- boolean equals(int[] a, int[] a2) int|long|short|char|byte|float|double|boolean
- void fill(long[] a, [int fromIndex, int toIndex,] iny val) int|long|short|char|byte|float|double|boolean
- <T> T[] copyOf(T[] original, int newLength)
- int[] copyOf(int[] original, int newLength) int|long|short|char|byte|float|double|boolean
- <T> T[] copyOfRange(T[] original, int from, int to)
- int[] copyOfRange(int[] original, int from, int to) int|long|short|char|byte|float|double|boolean
- <T> List<T> asList(T... a)
- int hashCode(int[] a) int|long|short|char|byte|float|double|boolean
- Array
Modifiers
- Access modifiers
- Non-access modifiers
Keywords
Identifiers
Garbage Collection
- under the control of the JVM; decides when to run it
- System.gc() ask the JVM to run the GC but no guarantees
- Make Objects Eligible for GC
- Nulling a Reference
- Reassigning a Reference Variable
- Isolating a Reference
- only thing guaranteed GC will run before it throws an OutOfMemoryException
- new Objcect.finalize() called only once to clean up resources before GC
- might run, but you can't count on it; don't override finalize() at all
- we can save an object from deletion inside it by making a reference to that object
- If the object becomes eligible for GC later it will not run again
Operators
- Assignment Operators
- Compound Assignment Operators
- Relational Operators
- "Equality" Operators
- Arithmetic Operators
- String Concatenation Operator
- Increment and Decrement Operators
- Ternary (Conditional Operator)
- Logical Operators
- Bitwise Operators: & 11, | (10,01,11), ^ (10,01)
- Short-Circuit Operators: &&, ||
- non-short-circuit Operators: &, | same as &&, || but evaluates both sides of the expression, always!
- Logical Operators ^ exclusive-OR, ! boolean invert
Enums
- c1 == c2 and c1.equals(c2) are equivalent
- for(CoffeeSize cs: CoffeeSize.values()) {}
Loops and Iterators
- while, do while, for
- for(Declaration and initialization of same type, boolean expression, iteration expression)
- declaration has loop scope not method
- evaluating iteration expression then the conditional expression then enter block
- all three sections are independent of each other: don't need to operate on the same variables
- for (int a = 1; b != 1; System.out.println("iterate"))
- for( ; ; ) endless loop
- for(Declaration and initialization of same type, boolean expression, iteration expression)
- The Enhanced for (Arrays & Collections) for(item declaration: array)
- Early Loop Termination: break, return, System.exit()
- continue must be inside a loop otherwise compile time error
- break must be inside a loop or swith statement otherwise compile time error
- Labeled Statements
- Labeled continue and break statements must be inside the loop that has the same label name, otherwise compile-time error
- break outer; (by default break inner)
- while, do while, for
Exceptions & errors
- try { do stuff } catch (SomeException ex) { do exception handling } finally { clean up }
- The optional finally block, it will always be invoked, regardless of whether an exception in the corresponding try is thrown or not, and regardless of whether a thrown exception is caught or not
- Except if JVM shuts down: code from the try or catch blocks calls System.exit()
- Just because finally is invoked does not mean it will complete. Code in the finally block could itself raise an exception or issue a System.exit().
- All catch blocks must be ordered from most specific to most general, otherwise not reached catch clauses
- a catch argument can catch the specified exception or any of its subtypes
- The optional finally block, it will always be invoked, regardless of whether an exception in the corresponding try is thrown or not, and regardless of whether a thrown exception is caught or not
- a try without a catch or finally is illegal
- legal to omit either the catch clause or the finally clause, but not both
- Uncaught Exceptions propagate
- Exception Hierarchy
- Object>Throwable>Exception>RuntimeException
- program errors
- rare, difficult-to-handle exceptional conditions
- Unchecked: not required to handle them even if declared
- ClassCastException, NullPointerException, ArrayIndexOutOfBoundsException, IllegalStateException, IllegalArgumentException, NumberFormatException
- Object>Throwable>Error
- unusual situations that are not caused by program errors
- things that would not normally happen during program execution
- Unchecked: not required to handle them even if declared
- OutOfMemoryError, VirtualMachineError, StackOverflowError, ExceptionInInitializerError, NoClassDefFoundError, AssertionError
- Object>Throwable>Exception
- Checked
- must be handled or declared
- FileNotFoundException, IOException
- Checked
- Object>Throwable>Exception>RuntimeException
- some other condition required for correct execution is not present
- can all be thrown using the throw Throwable keyword
- can all be caught
- Exception Matching
- throws declares the checked not yet handled exception
- can all be declared
- We can declare an exception that is not thrown in the method implementation or thrown but handled
- can Rethrow the Same handled Exception: catch(IOException e) { Do things, then if you decide you can't handle it… throw e; } you must declare it in this case.
- handle and declare, as opposed to handle or declare
- JVM Thrown Throwables: NullPointerException, StackOverflowError, ArrayIndexOutOfBoundsException, ClassCastException, ExceptionInInitializerError, NoClassDefFoundError
- Programmatically Thrown Exceptions: NumberFormatException, IllegalArgumentException, IllegalStateException, AssertionError
- try { do stuff } catch (SomeException ex) { do exception handling } finally { clean up }
switch statements rules
- can evaluate only to enums or the byte, short, int, and char data types
- The case constant must be a literal or final variable, or a constant expression, including an enum
- If the condition in a switch statement matches a case constant, execution will run through all code in the switch following the matching case statement until a break statement or the end of the switch statement is encountered.
- The default keyword should be used in a switch statement if you want to run some code when none of the case values match the conditional value.
- The default block can be located anywhere in the switch block, so if no case matches, the default block will be entered, and if the default does not contain a break, then code will continue to execute (fall-through) to the end of the switch or until the break statement is encountered.
Strings
- Immutable Objects
- charAt() concat() equalsIgnoreCase() length() replace() substring() toString() trim() toLowerCase() toUpperCase()
- special area of memory called the "String constant pool."
- Existing Strings simply have additional references, The reason why => String is immutable, marked final to not cause problems in the pool
- String s = new String("abc"); // creates two objects, and one reference variable
- StringBuffer and StringBuilder
- exactly the same API except StringBuilder is not thread safe: its methods are not synchronized
- StringBuilder will run faster
- StringBuffer append(String s) StringBuilder insert(int offset, String s) StringBuilder delete(int start, int end) StringBuffer reverse() String toString()
- exactly the same API except StringBuilder is not thread safe: its methods are not synchronized
- chained methods: x.concat("def").toUpperCase().replace('C','x')
I/O
- File: An abstract representation of file and directory pathnames
- String getName() String getParent() File getParentFile() String getPath() String getAbsolutePath() boolean canRead() boolean canWrite() boolean isDirectory() boolean isFile() boolean isHidden() long lastModified() boolean delete() void deleteOnExit() String[] list() File[] listFiles() boolean mkdir() boolean mkdirs() boolean renameTo(File dest) boolean setLastModified(long time)
- can't delete a directory unless it is empty
- boolean renameTo(File dest)
- file.renameTo(new File(dir, "newName.txt"));
- dir.renameTo(new File("newDir"));
- It's okay to rename a directory, even if it isn't empty
- NullPointerException if newName is null
- IOException
- new File("foo"); NEVER creates an actual file
- two ways to create a file
- file.createNewFile();
- Create a Writer or a Stream: FileWriter, PrintWriter, FileOutputStream
- two ways to create a file
- new File(myDir, "myFile.txt").createNewFile(); if no mkdir IOException: No such file or directory
- String getName() String getParent() File getParentFile() String getPath() String getAbsolutePath() boolean canRead() boolean canWrite() boolean isDirectory() boolean isFile() boolean isHidden() long lastModified() boolean delete() void deleteOnExit() String[] list() File[] listFiles() boolean mkdir() boolean mkdirs() boolean renameTo(File dest) boolean setLastModified(long time)
- FileReader: read character files
- usually wrapped by higher-level objects such as BufferedReaders, which improve performance and provide more convenient ways to work with the data
- long skip(long n) int read(char[] ) int read() void close()
- BufferedReader
- make lower-level Reader classe more efficient and easier to use
- read relatively large chunks of data from a file at once, and keep this data in a buffer
- next character or line of data, it is retrieved from the buffer
- minimizes the number of times that time-intensive, file read operations are performed
- += String readLine()
- FileWriter: write to character files
- Writer append(CharSequence csq) Writer append(char c) void write(int c) void write(char[] cbuf) void write(String str) void flush() void close()
- usually wrapped by higher-level Writer objects, which provide better performance and higher-level, more flexible methods to write data
- BufferedWriter: make lower-level Writer classes more efficient and easier to use
- BufferedWriters write relatively large chunks of data to a file at once, minimizing the number of times that slow, file writing operations are performed
- provides a += void newLine() method to create platform-specific line separators automatically
- PrintWriter: very flexible and powerful
- Writer += void_print[ln](boolean|char|int|float|double|char[]|String|Object) PrintWriter_printf([Locale l,]String format,Object... args) PrintWriter_format([Locale l,]String format, Object... args)
- Console: read input from the console and write formatted output to the console
- System .console() may be null if running in an environment that doesn't have access to a console object
- accept input from the command line, both echoed and nonechoed (such as a password): readLine vs readPassword
- readPassword method doesn't return a string: it returns a character array; If a string was returned, it could exist in a pool somewhere in memory and perhaps some nefarious hacker could find it
- char[] pw = c.readPassword("%s", "pw: ");
- c.readLine("%s", "input?: ");
- write formatted output to the command line
- Stream classes are used to read and write bytes
- Readers and Writers are used to read and write characters
- File: An abstract representation of file and directory pathnames
Serialization
- save this object and all of its instance variables
- new ObjectOutputStream(new FileOutputStream("f.out")).writeObject(Object) // serialize and write
- NotSerializableException if Object non transiant graphs are not all serializable
- new ObjectInputStream(new FileInputStream("f.in")).readObject() // read and deserialize
- new ObjectOutputStream(new FileOutputStream("f.out")).writeObject(Object) // serialize and write
- Object Graphs (dependencies hierarchy) should all be serializable
- if not use transient keyword to skip instance variables of non serializable classes
- subclass is not always an option
- class might be final
- class might itself refer to other non-serializable objects, and without knowing the internal structure
- other reasons related to your design
- subclass is not always an option
- if not use transient keyword to skip instance variables of non serializable classes
- private methods to implement, if present, will be invoked automatically during serialization and deserialization
- private void writeObject(ObjectOutputStream os) { }
- private void readObject(ObjectInputStream is) { }
- os.defaultWriteObject(); & is.defaultReadObject(); represent the normal serialization process for this object
- os.writeInt(theCollar.getCollarSize()); theCollar = new Collar(is.readInt());
- I/O-related methods writeObject() can throw exceptions. You can declare them or handle them but we recommend handling them.
- read the extra stuff in the same order you wrote it
- common reason: save some part of an object's state manually
- Object does NOT implement Serializable
- Class B extends A and A is Serializable => B is Serializable
- Deserialization process
- In deserialization process the constructor does not run, and instance variables are NOT given their initially assigned values
- transient instance variables get the default value according to their types
- instance variables INHERITED from NOT serializable classe are reset to the values they were given during the original construction of the object
- the nonserializable class no-argument constructor WILL run, if no such constructor InvalidClassException
- Not for Statics
- collection/array
- every element must be serializable
- collection interfaces are not serializable but concrete collection classes in java API are
- If you serialize an object using one version of the class, but attempt to deserialize it using a newer, different version of the class, deserialization might fail
- save this object and all of its instance variables
Dates, Numbers and Currency
- java.text package: format & parse for specific locale
- java.util.Locale: used in conjunction with DateFormat and NumberFormat to format dates, numbers and currency for specific locales
- Default locale is "EN", "US"
- set only at the time of instantiation for both DateFormat and NumberFormat objects
- Locale API
- new Locale(language[, country]);
- static Locale getDefault()
- static Locale[] getAvailableLocales()
- static String[] getISOCountries()
- static String[] getISOLanguages()
- String getLanguage()
- String getCountry()
- String getDisplayLanguage([Locale])
- String getDisplayCountry([Locale])
- java.text.DateFormat: format dates for locales
- Date: January 1, 1970
- DateFormat dateFormat = DateFormat.getDateInstance (style, locale);
- String formated = dateFormat.format(date);
- DateFormat API
- static DateFormat get(Time|Date)Instance([int style[,Locale]])
- static DateFormat getInstance()
- static DateFormat getDateTimeInstance([int dateStyle, int timeStyle[,Locale]])
- retain the time along with the date
- String format(Date date)
- Date parse(String source)
- ParseException
- Fields
- YEAR_FIELD MONTH_FIELD DATE_FIELD HOUR_OF_DAY1_FIELD HOUR_OF_DAY0_FIELD MINUTE_FIELD SECOND_FIELD MILLISECOND_FIELD
- DAY_OF_WEEK_FIELD DAY_OF_YEAR_FIELD WEEK_OF_MONTH_FIELD WEEK_OF_YEAR_FIELD AM_PM_FIELD
- Styles: FULL LONG MEDIUM SHORT DEFAULT
- Dates
- java.util.Date
- Most of its methods have been deprecated
- use it to bridge between the Calendar and DateFormat
- mutable date and time, to a millisecond
- new Date(): the current date and time value
- new Date([long]);
- java.util.Calendar: convert and manipulate dates and times
- Calendar is abstract
- Calendar API
- static Calendar getInstance([TimeZone|Locale|TimeZone, Locale])
- void setTime(Date date) Date getTime()
- void setTimeInMillis(long millis) long getTimeInMillis()
- void set(int field, int value) int get(int field)
- void set(int year, int month, int date[, int hourOfDay, int minute[, int second]])
- void clear([int field])
- boolean isSet(int field)
- String getDisplayName(int field, int style, Locale locale)
- void complete()
- int compareTo(Calendar anotherCalendar)
- void add(int field, int amount)
- void roll(int field, boolean up)
- void roll(int field, int amount)
- invoking roll() with MONTH won't change the year
- void setTimeZone(TimeZone value) TimeZone getTimeZone()
- Fields
- SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY
- JANUARY FEBRUARY MARCH APRIL MAY JUNE JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER
- YEAR MONTH WEEK_OF_YEAR WEEK_OF_MONTH DATE DAY_OF_MONTH DAY_OF_YEAR DAY_OF_WEEK AM_PM AM PM HOUR HOUR_OF_DAY MINUTE SECOND MILLISECOND
- ALL_STYLES SHORT LONG
- int getFirstDayOfWeek()
- calendar.add(Calendar.HOUR, -4);
- java.util.Date
- Numbers and Currency
- java.text.NumberFormat: format numbers and currencies for locales
- Number with new Locale("fr"): 1,000,999
- Currency: 10.000 $
- Currency with new Locale("fr"): 10,000 €
- NumberFormat is abstract
- NumberFormat API
- static NumberFormat get[Number|Integer|Percent|Currency]Instance([Locale]);
- String format(double|long)
- Number parse(String source)
- void set(Minimum|Maximum)IntegerDigits(int newValue)
- void set(Minimum|Maximum)FractionDigits(int newValue)
- Currency getCurrency()
- java.text.NumberFormat: format numbers and currencies for locales
Format, parse, find & replace and tokenize (strings or streams)
- tokenize data
- String.split method
- tokenize relatively small pieces of data
- String [] new String("...").split(regex)
- One drawback is that often you'll want to look at tokens as they are produced, and possibly quit a tokenization operation early when you've created the tokens you need
- java.util.Scanner
- Searching Using the Scanner Class
- primarily intended for tokenizing data but can also be used to find stuff, just like the Pattern and Matcher classes
- doesn't provide location information or search and replace functionality
- can tell you how many instances of an regex exist in a given piece of source data
- Scanner API
- void close()
- Scanner useDelimiter(Pattern|String pattern)
- Scanner reset()
- boolean hasNext()
- String next()
- boolean hasNextLine()
- String nextLine()
- String findInLine(Pattern|String pattern)
- Scanner skip(Pattern|String pattern)
- boolean hasNext(Boolean|Byte|Short|Int|Long|Float|Double|BigInteger|BigDecimal)()
- (boolean|byte|short|int|long|float|double|BigInteger|BigDecimal) next(Boolean|Byte|Short|Int|Long|Float|Double|BigInteger|BigDecimal)()
- on-the-fly tokenization operations
- When you need to do some serious tokenizing, look no further than Scanner
- Scanner class features
- can be constructed using files, streams, or Strings as a source
- Tokenizing is performed within a loop so that you can exit the process at any point
- Tokens can be converted to their appropriate primitive types automatically
- Scanner's default delimiter is whitespace
- taking big pieces of source data, breaking them into little pieces, and storing the little pieces in variables
- the most common tokenizing situation is reading a delimited file in order to get the contents of the file moved into useful places like objects, arrays or collections
- Data is composed of two things: tokens and delimiters
- Tokens: the actual pieces of data,
- Delimiters: the expressions that separate the tokens from each other.
- anything that qualifies as a regex expression
- when we tokenize source data, the delimiters themselves are discarded and all that we are left with are the tokens
- String.split method
- Regex
- A regex expression is like a very short program or script
- Regex engines search through textual data using instructions that are coded into expressions.
- The regex language is used to create expressions
- regex search rule
- a regex search runs from left to right
- once a source's character has been used in a match, it cannot be reused (consumed)
- Metacharacters
- \d: digit
- \s:whitespace character
- \w: word character (letters, digits, or "_" (underscore))
- Dot metacharacter: any character can serve here
- Constraints with strings
- "\d", "\." // compiler error!
- "\\d"; // a compilable metacharacter
- "."; // regex sees this as the "." metacharacter
- "\\."// dot, not a metacharacter
- Java escape sequences: \n = linefeed, \b = backspace, \t = tab, \u, \r
- Quantifiers
- Greedy
- +: one or more occurrences
- *: Zero or more occurrences
- ?: Zero or one occurrence
- looks (greedily) at the entire source data
- Reluctant
- +?: one or more occurrences
- *?: Zero or more occurrences
- ??: Zero or one occurrence
- Greedy
- Operators & syntax
- ^ operator: negate the characters specified
- [abc] : a, b, or c
- [^abc]: Any character except a, b, or c
- [a-zA-Z]: a through z or A through Z, inclusive
- [a-z&&[^bc]]: a through z, except for b and c
- nested brackets to create a union of sets
- && operator: specify the intersection of sets
- A common reason to use regex is to perform search and replace operations.
- Format
- PrintWriter.format/printf methods
- java.util.Formatter
- format string:%[arg_index$][flags][width][.precision] conversion char
- arg_index: which argument should be printed in this position
- flags:
- "-" Left justify
- "+" Include a sign (+ or -)
- "0" Pad with zeroes
- "," Use locale-specific grouping separators
- "(" Enclose negative numbers in parentheses
- width: the minimum number of characters to print including decimal point, sign and grouping separators
- precision: the number of digits to print after the decimal point for floating point numbers
- conversion char: b boolean, c char, d integer, f floating point, s string
- If mismatch between the type specified in the conversion character %d and the argument double: java.util.IllegalFormatConversionException: d != java.lang.Double
- Formatter API
- new Formatter(String|File|OutputStream)
- Formatter format([Locale l, ]String format, Object... args)
- format string:%[arg_index$][flags][width][.precision] conversion char
- java.io.PrintStream
- format() and printf() behave identically
- PrintStream API
- new PrintStream(String|File|OutputStream)
- PrintStream (printf|format)(String format, Object... args)
- Find & replace
- java.util.regex.Pattern
- static Pattern compile(String regex)
- Matcher matcher(CharSequence input)
- static boolean matches(String regex, CharSequence input)
- String[] split(CharSequence input)
- java.util.regex.Matcher
- Matcher m = p.matcher(String source_data); while(m.find()) { }
- Matcher API
- Pattern pattern()
- int start(): the start index of the previous match
- int end(): the offset after the last character matched
- String group(): the input subsequence matched by the previous match
- boolean find(): find the next subsequence of the input sequence that matches the pattern
- Matcher appendReplacement(StringBuffer sb, String replacement)
- StringBuffer appendTail(StringBuffer sb)
- String replaceAll(String replacement)
- m.group() and s.substring(m.start(), m.end()) are equivalent
- Zero-length matches in m.group()
- After the last character of source data
- In between characters after a match has been found
- At the beginning of source data
- At the beginning of zero-length source data
- Regions
- Regions: The Matcher class allows you to look at subsets of your source data by using a concept called regions
- regions can greatly improve performance
- java.util.regex.Pattern
- tokenize data
Generics
- To enforce compile-time type safety on classes and methods declared using generic type parameters
- An ArrayList<Animal> can accept references of type Dog, Cat, or any other subtype of Animal (subclass, or if Animal is an interface, implementation).
- When using generic collections, a cast is not needed to get (declared type) elements out of the collection. With non-generic collections, a cast is required
- You can pass a generic collection (you originally declared as type-safe) into a method that takes a non-generic collection, but the results may be disastrous.
- The compiler can't stop the method from inserting the wrong type into the previously type safe collection
- non-type-safe code
- compiler warning
- Type safe Collection
- The generics mechanism in the language provides compile-time (static) type checking, but it is possible to defeat this mechanism with unchecked casts.
- Generic type information does not exist at runtime—it is for compile-time safety only
- Mixing generics with legacy code can create compiled code that may throw an exception at runtime
- Polymorphic assignments applies only to the base type, not the generic type parameter
- List<Animal> aList CANNOT take a List<Dog>
- List<Animal> bar() { } CANNOT return a List<Dog>
- Wildcard syntax: allows a generic method/constructor argument to accept subtypes (or supertypes) of the declared type of the method/constructor argument
- extends is used to mean either "extends" or "implements."
- in <? extends Dog>, Any type extending or implementing Dog including Dog
- in <? super Dog>, Any type super class of Dog inluding Dog and Object
- When declaring a reference using a wildcard, List<? extends Dog> or List<?>, the collection can be accessed but not modified.
- List<? extends Animal> list = new ArrayList<Dog>(); is LEGAL but list.add(any animal even if aHorse); is ILLEGAL; compile-time error to guarantee type safety - the only possible value is null -
- List<? extends Object> and List<?> are absolutely identical
- When using a wildcard, List<?>, any generic type can be assigned to the reference, but for access only, no modifications.
- List<Object> refers only to a List<Object>, while List<?> or List<? extends Object> can hold any type of object, but for access only.
- Declaration conventions for generics use T for type and E for element
- The generics type identifier can be used in class, method, and variable declarations
- class Foo<t> { } // a class
- T anInstance; // an instance variable
- Foo(T aRef) {} // a constructor argument
- void bar(T aRef) {} // a method argument
- T baz() {} // a return type
- The compiler will substitute the actual type
- You can use more than one parameterized type in a declaration: public class UseTwo<T, X> { }
- You can declare a generic method using a type not defined in the class: public <T> void makeList(T t) { } before the return type
Inner classes
- "Regular" Inner Class: inner class that is not Static, Method-local, Anonymous
- an inner class instance has access to all members of the outer class, even those marked private, as if the inner class were part of the outer class
- if you wrote the outer class, then you also wrote the inner class! So you're not violating encapsulation; you designed it this way
- Simulate the forbidden multiple inheritance
- inner class instance shares a "special relationship" with an instance of the outer class
- the inner class is a part of the outer class. Not just a "part" but a full-fledged, card-carrying member of the outer class.
- class MyOuter { class MyInner { } }
- %javac MyOuter.java MyOuter.class MyOuter$MyInner.class
- You can't say %java MyOuter$MyInner: the inner class file isn't accessible in the usual way
- can't have static declarations of any kind
- The only way you can access the inner class is through a live instance of the outer class!
- Instantiating an Inner Class
- from Within the Outer Class: MyInner in = new MyInner();
- MyOuter mo = new MyOuter(); MyOuter.MyInner inner = mo.new MyInner();
- the rules for an inner class referencing itself or the outer instance
- Use this to reference the inner class instance itself, from within the inner class code
- use NameOfOuterClass.this To reference the "outer this" (the outer class instance) from within the inner class code
- A regular inner class is a member of the outer class just as instance variables and methods are
- Member Modifiers Applied to Inner Classes
- public private protected No access modifier: default
- final abstract strictfp
- static: but static turns it into a static nested class not an inner class
- this keyword
- The keyword this can be used only from within instance code. In other words, not within static code.
- The this reference is a reference to the currently executing object. In other words, the object whose reference was used to invoke the currently running method.
- The this reference is the way an object can pass a reference to itself to some other code, as a method argument
- Method-Local Inner Classes
- can be instantiated only within the method where the inner class is defined below the inner class definition (or the compiler won't be able to find the inner class)
- Like regular inner class objects, the method-local inner class object shares a special relationship with the enclosing (outer) class object, and can access its private (or any other) members
- the inner class object cannot use the local variables of the method the inner class is in
- The local variables of the method live on the stack, and exist only for the lifetime of the method but the inner class object lives on the heap (may still alive after after the method completes if, for example, a reference to it was passed into some other code and then stored in an instance variable)
- Because the local variables aren't guaranteed to be alive as long as the method-local inner class object, the inner class object can't use them.
- Unless the local variables are marked final
- Compile error: local variable z is accessed from within inner class; needs to be declared final
- Method-Local inner classe declared in a static method
- has access to only static members of the enclosing class
- there is no this
- Method-Local inner classe in a static method is subject to the same restrictions as the static method
- no access to instance variables
- Anonymous Inner Class
- Comes in two flavors from class & from interface
- Popcorn p = new Popcorn() {};
- refers not to an instance of Popcorn, but to an instance of an anonymous (unnamed) subclass of Popcorn
- The whole point is to override one or more methods of the superclass or to implement methods of an interface
- Polymorphism is in play when anonymous inner classes are involved
- can implement only one interface
- Cannot add public methods other than the overridden ones
- Argument-Defined Anonymous Inner Class
- declare and instanciate an Anonymous inner class as a parameter value
- automatically becomes an implementer of any interfaces implemented by the superclass
- Static Nested Classes
- they really aren't inner classes at all
- does not share a special relationship with the outer class
- It is simply a non-inner (also called "top-level") class scoped within another
- it's really more about name-space resolution than about an implicit relationship between the two classes
- simply a class that's a static member of the enclosing class
- does not have access to the instance variables and nonstatic methods of the outer class
- from Within the Outer Class: Nested n = new Nested() Outside the Outer class: Outer.Nested n = new Outer.Nested();
- "Regular" Inner Class: inner class that is not Static, Method-local, Anonymous
Threads
- java.lang.Thread: implements Runnable
- Thread t = new Thread(new MyThread()); // This is a bit silly, but it’s legal.
- new Thread([Runnable target])
- new Thread(Runnable target,String name)
- static final int MIN_PRIORITY
- static final int NORM_PRIORITY
- static final int MAX_PRIORITY
- static Thread currentThread()
- static void yield()
- static void sleep(long millis[, int nanos]) throws InterruptedException
- void start()
- A new thread of execution starts (with a new call stack)
- The thread moves from the new state to the runnable state
- When the thread gets a chance to execute, its target run() method will run
- Once a thread has been started, it can never be started again: IllegalThreadStateException
- void run()
- A thread is considered dead (no longer alive) after the run() method completes.
- t.run(); // Legal, but does not start a new thread
- void interrupt()
- static boolean interrupted()
- static boolean holdsLock(Object obj)
- boolean isInterrupted()
- final boolean isAlive()
- final void setPriority(int newPriority)
- final void setName(String name)
- Even if you don't explicitly name a thread, it still has a name. main, Thread-0, Thread-1
- final String getName()
- final void join([long millis[, int nanos]]) throws InterruptedException
- final void setDaemon(boolean on)
- low priority thread
- JVM terminates itself when all user non daemon threads finish their execution
- final boolean isDaemon()
- StackTraceElement[] getStackTrace()
- Thread.State getState()
- very useful for debugging
- java.lang.Runnable
- The action happens in its run() method
- public void run() { // your job code goes here }
- two different things:
- An instance of class java.lang.Thread
- A thread of execution
- individual process that has its own call stack
- one call stack per thread
- The main() method runs in one thread: the main thread
- threads run concurrently with the main thread
- The JVM operates like a mini-OS and schedules its own threads regardless of the underlying operating system
- most JVMs map Java threads directly to native threads on the underlying OS
- When it comes to threads, very little is guaranteed.
- define and instantiate a thread
- Extend the java.lang.Thread class
- not a good OO practice: subclassing should be reserved for specialized versions of more general superclasses
- Implement the Runnable interface
- leaves your class free to extend from some other class
- Extend the java.lang.Thread class
- Thread Scheduler
- part of the JVM
- decides which thread should run at any given moment
- takes threads out of the run state
- Only threads in the runnable state are eligible to be the currently running thread
- Although queue behavior is typical, it isn't guaranteed
- The order in which runnable threads are chosen to run is not guaranteed.
- we call it a runnable pool, rather than a runnable queue
- we can sometimes influence it wa CANNOT control it
- Methods from the java.lang.Thread Class that can help us influence thread scheduling
- public static void sleep(long millis) throws InterruptedException
- public static void yield()
- public final void join() throws InterruptedException
- public final void setPriority(int newPriority)
- Methods from the java.lang.Object Class that can help us influence thread scheduling
- public final void wait() throws InterruptedException
- public final void notify()
- public final void notifyAll()
- Methods from the java.lang.Thread Class that can help us influence thread scheduling
- Thread States
- New
- the Thread instance has been created, but the start() method has not been invoked on the thread
- Thread object, but not yet a thread of execution
- considered not alive
- Runnable
- eligible to run, but the scheduler has not selected it to be the running thread
- A thread first enters the runnable state when the start() method is invoked
- a thread can also return to the runnable state after either running or coming back from a blocked, waiting, or sleeping state
- considered alive
- Running
- when the thread scheduler selects it (from the runnable pool) to be the currently executing process
- only one way to get to the running state: the scheduler chooses a thread from the runnable pool
- Waiting/blocked/sleeping
- still alive, but is currently not eligible to run
- might return to a runnable state later if a particular event occurs
- A thread may be blocked waiting for a resource (like I/O or an object's lock), in which case the event that sends it back to runnable is the availability of the resource
- A thread may be sleeping because the thread's run code tells it to sleep for some period of time, in which case the event that sends it back to runnable is that it wakes up because its sleep time has expired.
- A thread may be waiting, because the thread's run code causes it to wait, in which case the event that sends it back to runnable is that another thread sends a notification that it may no longer be necessary for the thread to wait.
- Dead
- when its run() method completes
- is still a Thread object, but it no longer a separate thread of execution
- can never be brought back to life
- New
- one thread does not tell another thread to block
- If you have a reference t to another thread, you can write something like this: t.sleep(); or t.yield() But those are actually static methods of the Thread class—they don't affect the instance t; instead they are defined to always affect the thread that's currently executing.
- a good example of why it's a bad idea to use an instance variable to access a static method—it's misleading
- java.lang.Thread: implements Runnable
Informações
- Descrição
- Mapa Mental sobre XSPELSODE, criado por Abdelkrim ZAHMOUNI em 23-09-2018.
- Criado por
- Abdelkrim ZAHMOUNI
- Visualizações
- 0
- Avaliação