SCJP 5.0 Study Notes(1)

Note:   Please feel free to modify, improve, circulate, and repost these notes at will.   Dave Allen

 

Collections Framework (only Maps, Iterators do not extend java.io.Collection Interface)

Collection interface

add(E)

addAll (Collection<e>)

remove(Object)

removeAll ( Collection<?>)

contains(Object)

size()

iterator ()

isEmpty ()

Object[] toArray () – returns Object array, must cast – e.g. String[] str = (String[]) myCollection.toArray ();

T[] toArry (T[] a) – returns typecast array – syntax: String[] str = myCollection.toArray (new String[0]);

Map interface,

SortedMap interface extends Map

put(keyObject , valueObject ) – inserts key/value pair, will overwrite duplicate keyObject values

keySet () – returns set of keys

values() – returns collection of values

get(Object), remove(Object), size(), clear()

entrySet () – returns set of Map.Entry type (key/value pair)

Map.Entry – a key/value pair, has getKey () and getValue () methods

 

Maps care about unique identifiers

There is no add() method; Don’t have to override equals(Object) method to compile, but necessary to find objects

HashMap

 

Hashtable

synchronized version of HashMap

TreeMap

Can have null values, but NO null keys

LinkedHashMap (extends Hashmap )

maintains insertion order, slower updates, faster iteration than HashMap , order remains same if replacing duplicate key, can have null keys or values

Set interface, SortedSet interface extends Set

boolean add() – if element already exists, returns false and element not added

Sets care about uniqueness

HashSet

 

LinkedHashSet (extends HashSet )

fastest iteration through items without duplicates (a Set) that maintains insertion order

TreeSet <T>

new TreeSet (), new TreeSet (Collection<E>), new TreeSet <T>(Comparator<? super E>)

List interface

Lists care about the index

ArrayList

fastest iteration through items with duplicates

Vector

synchronized version of ArrayList ; slower

LinkedList

addFirst (), getFirst ()

 

doubly linked, ideal for implementing a stack or maintaining an ordered sequence of objects when they are frequently inserted and removed from the middle of the sequence

Queu interface

peek() – returns highest priority entry without removing it

poll() – returns highest priority entry and removes it

offer() – adds entry

PriorityQue

 

Collections

Collections.sort (Collection)

Collections.sort (Collection, Comparator)

Collections.binarySearch (collectionName , pattern) – must be sorted first

Collections.binarySearch (collectionName , pattern, Comparator) – must be sorted first

Collections.reverse () – reverses order of elements in List, doesn’t have to be sorted first

Collections.reverserOrder () – returns Comparator that sorts in reverse, must b sorted first

Arrays

Arrays.sort (arrayToSort )

Arrays.binarySearch (arrayName , pattern), Arrays.binarySearch (collectionName , pattern, Comparator) – returns int index

Arrays.asList (arrayName ) – returns List, changes to either returned list or original array will be reflected in the other

Comparable interface

int compareT o (SpecificObject Type )

returns     negative int if this < Obj2

                0 if Objects are equal

                positive int if this > Obj2

Comparator class

int compare(SpecificObject Type1, SpecificObject Type2) – returns int with same meaning as above – substitute “SpecificObjectType1” for “this”

Iterator

boolean hasNext ()

next() – returns type Object which must be cast if no generic type is specified for iterator , even if Collection that called iterator () method has generics, like List<Integer>

 

Can use generics syntax to avoid explicit casting, e.g. Iterator <Dog> = dogs.iterator ();

 

 


Dates

java.util.Date

new Date() – date Object with current date

new Date(long millis ) – millis since Jan 1, 1970

 

getTime () – returns long

setTime (long millis )

 

internally stored as primitive long which is milliseconds between date and Jan 1, 1970

Calendar

Calendar.getInstance () – gets default Calendar (almost always GregorianCalendar ) with current time

Calendar.getInstance (Locale)

 

add( intField , intAmount ) – adds or decrements field.  intAmount can be negative

roll(intField , intAmount ) – larger parts of date will not be incremented/decremented, only the field specified

set(intField , intValue )

get(intField ) – e.g. calendarInstance.get (Calendar.MONTH );

set() – various other set methods

setTime (Date)

getTime () – returns Date object, useful for passing to DateFormat

setTimeInMillis (long millis )

getTimeInMillis () – returns long

compareTo (Calendar)

 

NO new Calendar(), only instantiated using getInstance (), months are 0-based (January is 0)

java.text .

NumberFormat

NumberFormat.getInstance (), NumberFormat.getInstance (Locale) – e.g. NumberFormat.getInstance (Locale.US );

NumberFormat.getNumberInstace ( ), NumberFormat.getNumberInstanceLocale () – same as getInstance ()?

NumberFormat.getCurrencyInstance (), NumberFormat.getCurrencyInstance (Locale)

 

format(long), format(double) – takes various numbers to be formatted, returns String

parse(String) – takes a String (must be formatted correctly to locale), returns a Number – e.g. parse(“$5,075”);

setParseIntegerOnly ( boolean ) – whether to format and display digits after decimal.

getMaximumFractionDigits (), getMinimumFractionDigits – get number of decimal places

setMaximumFractionDigits (int), setMinimumFractionDigits – set number of decimal places

get/setMinimum/MaximumIntegerDigits ()

 

Should only instantiated using getInstance ()

java.text . DateFormat

getInstance () – returns DateFormat with default Locale, sometimes SHORT style

getDateInstance () (has defaults, sometimes MEDIUM style),getDateInstance (styleConstant ), getDateInstance (styleConstant , Locale)

parse(String) – converts String to a Date

format(Date) – returns String with formatted Date

 

String format for each style

possible default format – 0/8/01 7:46 PM

DateFormat.SHORT   9/8/01

DateFormat.MEDIUM – Sep 8, 2001

DateFormat.LONG – September 8, 2001

DateFormat.FULL – Saturday, September 8, 2001

 

There is no format( Calendar) method.  Calendar must convert to Date first(using yourCalendar.getTime ()), then use format(Date)

DateFormat’s Locale can only be set at instantiation using getInstance () – NO new DateFormat ()

java.util.Locale

Locale.getDefault () – returns default Locale

new Locale(stringLanguage )

new Locale(stringLanguage , stringCountry ) – e.g. new Locale(“it”, “IT”)

 

setDefault (Locale)

getDisplayLanguage () – returns String of Language

getDisplayLanguage (Locale) – displays language using language of Locale passed in

getDisplayCountry () – returns String code

getDisplayCountry (Locale) – displays language using language of Locale passed in)

Locale.getAvailableLocales () – returns an array of Locales installed

 

used in Scanner, DateFormat , NumberFormat

 


String Stuff

String

new String(), new String(StringBuilder /Buffer)

new String(“StringLiteral ”)

new String(ExistingStringObject ) will create a new String object different than ExistingStringObject

 

length()

charAt (int)

concat (String)

equalsIgnoreCase (String)

substring(intIndex )

substring(startIntIndex , endIntIndexExclusive )

replace(char/stringRegex , char/stringReplacement )

replaceAll (char/stringRegex , char/stringReplacement )

replaceFirst (stringRegex , stringReplacement )

split(regex ) – returns String array of tokens, good for just small amount of data

split(regex , IntLengthOfArrayReturned )

toLowerCase ()

toUpperCase ()

trim() – remove whitespace off ends

toString () – returns a new String object

 

indexOf (char/String)

indexOf (char/String, startingIntIndex )

lastIndex (char/String, startingIntIndex )

lastIndex (char/String, startingIntIndex )

contains(charSequence )

matches(regex ) – returns boolean indicating if regex matches string

boolean startsWith (String)

boolean startsWith (String, offsetIndex )

String format(“formattingString ”, args ) – returns String formatted to specs

String format(Locale, “formattingString ”, args )

 

All methods return a String, do no alter original String

NO insert() method (this is in StringBuilder/StringBuffer )

NO length member variable (this is for array)

StringBuilder / StringBuffer

append(xxx) – can append almost any char related type

delete(intStartIndex , intEndIndexExclusive )

deleteCharAt ()

insert(intOffset , String)

reverse()

toString ()

length()

substring(startIndexInclusive )

substring(startIndex , endIndexProbablyExclusive )

 

lastIndexOf (String)

lastIndexOf (String, startSearchIndex )

replace(intStart , intEnd , String)

setCharAt ()

 

StringBuffer is synchronized and slower.

StringBuilder is not synchronized and faster

equals() method is not overridden, so it compares references, not meaningful values – same as ==

java.util .

Scanner

new Scanner(File), new Scanner(stringToSearchOrTokenize )

 

useDelimiter (String) – can be regex

useLocal (Locale)

hasNext (), hasNextInt (), hasNextFloat (), hasNextXxx () – for all primitives EXCEPT char

next(), nextInt (), nextFloat (), nextXxx – for all primitives EXCEPT char

Scanner.close () – static method that should be used after done with file

findInLine (regexString ) – returns String found

 

match() – returns MatchResult

matchResult.groupCount () – method in MatchResult (not Scanner)

matchResult.group (groupCountIndexInt ) – method in MatchResult (not Scanner)

 

Mostly used for tokenizing, but can also find regexes using findInLine ()

Default delimiter is whitespace

java.util.regex .

Pattern

Pattern.compile (regex ) – returns new Pattern

matcher(CharSequence ) – returns new Matcher

split(regex ) – returns String array of matching patterns found in the CharSequence

Pattern.matches (regex , stringtoSearch ) – returns Boolean indicating if string matches regex

 

/d             digits

/s             whitespace

/w            word character (letters, digits, or underscores)

  [af ]         a or f

  [a-f]        a, b, c, d, e, f

  [a-dA -D]                A,a,B,b,C,c,D,d

.               any character

+              greedy one or more (e.g. /d+ means one or more digits)

*              greedy zero or more (e.g. filename/d*)

?              greedy zero or more occurrences(e.g. /d?)

^              not (e.g. [^abc ] excludes abc )

 

String pattern = “\\d” creates string regex with \d.  String pattern = “\\.” creates string regex with .

java.util.regex .

Matcher

find() – returns boolean indicating a match’s existence, advances to next index that matches, left to right

start() – returns starting index

group() – returns string that matches

 

Probably Not on Exam

replaceAll (stringReplacement )

replaceFirst (stringReplacement )

appendReplacement (StringBuffer , stringReplacement ) --

appendTail (StringBuffer ) – to be used after appendReplacement

java.util .

Formatter

new Formatter(), new Formatter(Appendable , Locale) – Appendable can be StringBuilder/StringBuffer ,

BufferedWriter , FileWriter , but NOT String

 

format(“formattingString ”, args ) – returns formatted String

 

Serialization (package java.io , classes must implement Serializable to be serialized)

FileOutputStream

new FileOutputStream (stringFileName )

new FileOutputStream (File)

ObjectOutputStream

defaultWriteObject ()

writeObject (Object)

writeInt (int), writeFloat (float), writeXxx (xxx)

FileInputStream

new FileInputStream (stringFileName )

new FileInputStream (File)

ObjectInputStream

defaultReadObject ()

readObject () – returns Object, must be cast before use

readInt (), readFloat (), readXxx ()

 

 转自

<!---->     <!---->

你可能感兴趣的:(F#)