Hier werden die Unterschiede zwischen zwei Versionen angezeigt.
Beide Seiten der vorigen Revision Vorhergehende Überarbeitung Nächste Überarbeitung | Vorhergehende Überarbeitung | ||
becki:linux:sunkurs [2007-05-21 11:59] 127.0.0.1 external edit |
becki:linux:sunkurs [2010-10-19 12:39] (aktuell) becki |
||
---|---|---|---|
Zeile 1: | Zeile 1: | ||
- | ====== Links ====== | + | ====== SCJP Infos ====== |
+ | ===== Links ====== | ||
[[java]] | [[java]] | ||
- | ====== Language Fundamentals ====== | + | ===== Language Fundamentals ====== |
- | [[javatut>java/nutsandbolts/datatypes.html|Table of Primitive Data Types]] | + | [[javatut>java/nutsandbolts/datatypes.html|Table of Primitive Data Types]] | [[javatut>java/nutsandbolts/_keywords.html|Java Language Keywords]] |
- | [[javatut>java/nutsandbolts/_keywords.html|Java Language Keywords]] | + | |
- | ===== unsorted ===== | + | ==== unsorted ===== |
* The default constructor initializes the base classes automatically | * The default constructor initializes the base classes automatically | ||
Zeile 18: | Zeile 18: | ||
* char can be converted to int (32 Bits) but not to short (16 Bits) | * char can be converted to int (32 Bits) but not to short (16 Bits) | ||
- | ===== Arrays ===== | + | ==== Arrays ===== |
* Multidimensinal arrays don't have to be rectangular! | * Multidimensinal arrays don't have to be rectangular! | ||
Zeile 32: | Zeile 32: | ||
</code> | </code> | ||
- | ===== Initalization Values ===== | + | ==== Initalization Values ===== |
* Instazvariablen werden automatisch mit 0 vorbelegt | * Instazvariablen werden automatisch mit 0 vorbelegt | ||
Zeile 42: | Zeile 42: | ||
* long l=6 works, but Long l=6 not, because autoboxing calls Long constuctor which expects only long or String! | * long l=6 works, but Long l=6 not, because autoboxing calls Long constuctor which expects only long or String! | ||
- | ====== 1. Declarations and Access Control ====== | + | ===== 1. Declarations and Access Control ====== |
- | ===== Declarations ===== | + | ==== Declarations ===== |
* A static method can //not// call a nonstatic method, but the other way around is possible | * A static method can //not// call a nonstatic method, but the other way around is possible | ||
Zeile 54: | Zeile 54: | ||
* Main method must be ''public static void main(String[] args)'' but this ''public static strictfp synchronized final void main(String[] args) throws Exception'' will also compile and run (tested) | * Main method must be ''public static void main(String[] args)'' but this ''public static strictfp synchronized final void main(String[] args) throws Exception'' will also compile and run (tested) | ||
- | ==== Allowed modifiers for variables and methods: ==== | + | === Allowed modifiers for variables and methods: ==== |
| ^final ^public ^protected ^private ^static ^transient ^volatile ^abstract ^synchronized ^strictfp ^native ^ | | ^final ^public ^protected ^private ^static ^transient ^volatile ^abstract ^synchronized ^strictfp ^native ^ | ||
^local variables |IYES |INO |INO |INO |INO |INO |INO |INO |INO |INO |INO | | ^local variables |IYES |INO |INO |INO |INO |INO |INO |INO |INO |INO |INO | | ||
Zeile 61: | Zeile 61: | ||
*)Only possible combinations with **abstract**: **public** and **protected**, nothing else! (tested) | *)Only possible combinations with **abstract**: **public** and **protected**, nothing else! (tested) | ||
- | ===== Packages ===== | + | ==== Packages ===== |
* import blah.* schliesst nur alle Klassen des Packages blah, nicht jedoch Sub-Packages ein | * import blah.* schliesst nur alle Klassen des Packages blah, nicht jedoch Sub-Packages ein | ||
Zeile 68: | Zeile 68: | ||
* A Class can be public or not public. If public, it can be made visible in other packages (in addition to public it can als be abstract or final and strictfp (floating point)) | * A Class can be public or not public. If public, it can be made visible in other packages (in addition to public it can als be abstract or final and strictfp (floating point)) | ||
- | ===== Interfaces ===== | + | ==== Interfaces ===== |
* Interface variables must be initialized when declarated (tested) | * Interface variables must be initialized when declarated (tested) | ||
* Interface variables are implicitly **public static final** and must not be anything else! (tested) | * Interface variables are implicitly **public static final** and must not be anything else! (tested) | ||
Zeile 77: | Zeile 77: | ||
* Because interface methods are public the implementing methods must also be public! | * Because interface methods are public the implementing methods must also be public! | ||
- | ===== Abstract Classes ===== | + | ==== Abstract Classes ===== |
* An abstract class can claim to implement an interface but doesn't need to mention the methods of that interface at all! | * An abstract class can claim to implement an interface but doesn't need to mention the methods of that interface at all! | ||
Zeile 86: | Zeile 86: | ||
* concrete methods of superclass can be declared abstract by subclasses | * concrete methods of superclass can be declared abstract by subclasses | ||
- | ====== 2. Object Orientation ====== | + | ===== 2. Object Orientation ====== |
- | ===== Benefits of Encapsulation == | + | ==== Benefits of Encapsulation == |
Maintainability, flexibility and extensibility: | Maintainability, flexibility and extensibility: | ||
Zeile 93: | Zeile 93: | ||
* Code is easier to reuse | * Code is easier to reuse | ||
- | ===== Overridden and Overloaded Methods == | + | ==== Overridden and Overloaded Methods == |
^ Method is ^ overloaded ^ overwritten ^ | ^ Method is ^ overloaded ^ overwritten ^ | ||
Zeile 105: | Zeile 105: | ||
- | ==== Overriding Methods ===== | + | === Overriding Methods ===== |
This is polymorphism. | This is polymorphism. | ||
Zeile 114: | Zeile 114: | ||
* Private and final methods cannot be overwritten | * Private and final methods cannot be overwritten | ||
- | ==== Overloading Methods ===== | + | === Overloading Methods ===== |
Overloading means different methods with same name (wich do the same) but with different argument list. | Overloading means different methods with same name (wich do the same) but with different argument list. | ||
Zeile 124: | Zeile 124: | ||
* Overloading can happen in the same class or in a subclass | * Overloading can happen in the same class or in a subclass | ||
- | ==== Overloading with Boxing and Varargs ===== | + | === Overloading with Boxing and Varargs ===== |
<code java> | <code java> | ||
Zeile 140: | Zeile 140: | ||
* box and than widen is possible: Eg an int can become an Object (via Integer) | * box and than widen is possible: Eg an int can become an Object (via Integer) | ||
- | ===== Constructors and Instantiation == | + | ==== Constructors and Instantiation == |
* The **first call** in a constructor of any class other than Object must //either// be this(...), i.e. calling another constructor, in the same class, //or// super(...), i.e. calling a constructor of the base class. If omitted, super() is inserted automatically. | * The **first call** in a constructor of any class other than Object must //either// be this(...), i.e. calling another constructor, in the same class, //or// super(...), i.e. calling a constructor of the base class. If omitted, super() is inserted automatically. | ||
Zeile 153: | Zeile 153: | ||
* Constructors can be called only from within another constructor | * Constructors can be called only from within another constructor | ||
- | ===== Reference Variable Casting == | + | ==== Reference Variable Casting == |
<code java> | <code java> | ||
Zeile 169: | Zeile 169: | ||
</code> | </code> | ||
- | ====== 3. Assignments and 4. Operators ====== | + | ===== 3. Assignments and 4. Operators ====== |
- | ===== Converting and Casting ===== | + | ==== Converting and Casting ===== |
- | ==== Primitive Data Types ==== | + | === Primitive Data Types ==== |
* all operations are on base of int, thus byte and short are automatically converted to int | * all operations are on base of int, thus byte and short are automatically converted to int | ||
Zeile 190: | Zeile 190: | ||
| long operation | long | double operation | double | | | long operation | long | double operation | double | | ||
- | ==== Reference Types ==== | + | === Reference Types ==== |
* cast to interface type is always possible, because any subclass of class could somewhen implement the interface; exception: class is final and does not implement the interface | * cast to interface type is always possible, because any subclass of class could somewhen implement the interface; exception: class is final and does not implement the interface | ||
* An array in java is an object, that implements clonable and serializable | * An array in java is an object, that implements clonable and serializable | ||
- | ==== Shadowing and Stack Variables ==== | + | === Shadowing and Stack Variables ==== |
<code java> | <code java> | ||
Zeile 209: | Zeile 209: | ||
If the class variable would not exist (A), the code would not compile at (B), because the automatic variable (C) doesn't exist until it's ceated in the code (tested) | If the class variable would not exist (A), the code would not compile at (B), because the automatic variable (C) doesn't exist until it's ceated in the code (tested) | ||
- | ===== Comparison Operators ===== | + | ==== Comparison Operators ===== |
* Array of primitives are objects too! | * Array of primitives are objects too! | ||
Zeile 218: | Zeile 218: | ||
* Object reference variables only of the same type or if one is the base type (implements or extends) of the other (tested) | * Object reference variables only of the same type or if one is the base type (implements or extends) of the other (tested) | ||
- | ===== Arithmetic Operators ===== | + | ==== Arithmetic Operators ===== |
* (anyInteger / 0) or modulo causes runtime exception, not compiletime error | * (anyInteger / 0) or modulo causes runtime exception, not compiletime error | ||
* Division by 0.0 (floating p.) causes no exception, but infinity | * Division by 0.0 (floating p.) causes no exception, but infinity | ||
- | ===== Logical Operators ===== | + | ==== Logical Operators ===== |
* op1&&op2 ; op1||op2 : only boolean operators possible (if (5 && 6) ... will NOT comile!), evaluates op2 only if necessary | * op1&&op2 ; op1||op2 : only boolean operators possible (if (5 && 6) ... will NOT comile!), evaluates op2 only if necessary | ||
* op1&op2 ; op1|op2 : eighter only boolean operators (inefficient!) or only numbers (bitwise then); always evaluates op2 | * op1&op2 ; op1|op2 : eighter only boolean operators (inefficient!) or only numbers (bitwise then); always evaluates op2 | ||
- | ===== instanceof ===== | + | ==== instanceof ===== |
* instanceof kann bei einem Downcast zum vorherigen Test verwendet werden | * instanceof kann bei einem Downcast zum vorherigen Test verwendet werden | ||
* Type of tested object (before instanceof-operator) and Class/Interface (after instanceof-operator) must lie in the same inheritance chain, otherwise it won't compile (tested 2006-02-10) | * Type of tested object (before instanceof-operator) and Class/Interface (after instanceof-operator) must lie in the same inheritance chain, otherwise it won't compile (tested 2006-02-10) | ||
- | ===== Bit Shift ==== | + | ==== Bit Shift ==== |
INO not tested any more! | INO not tested any more! | ||
Zeile 240: | Zeile 240: | ||
* %%<<<%% doen't exist | * %%<<<%% doen't exist | ||
- | ====== 5. Flow Control, Exceptions and Assertions ====== | + | ===== 5. Flow Control, Exceptions and Assertions ====== |
- | ===== Loops ===== | + | ==== Loops ===== |
- | ==== Continue and Break ==== | + | === Continue and Break ==== |
* ''continue'' must always be inside a loop(for, while, do while), otherwise compiler error | * ''continue'' must always be inside a loop(for, while, do while), otherwise compiler error | ||
Zeile 251: | Zeile 251: | ||
* **Labeled ''continue'' and ''break'' statements must be somewhere inside the loop that has the same label name, otherwise the code will not compile** | * **Labeled ''continue'' and ''break'' statements must be somewhere inside the loop that has the same label name, otherwise the code will not compile** | ||
- | ==== Enhanced For Loop ==== | + | === Enhanced For Loop ==== |
* Block variable must always declared newly | * Block variable must always declared newly | ||
* Autoboxing possible | * Autoboxing possible | ||
- | ==== For Loop ==== | + | === For Loop ==== |
* more than one command can be separated by ',' in 1st (initialization)? and 3rd (iteration) field | * more than one command can be separated by ',' in 1st (initialization)? and 3rd (iteration) field | ||
Zeile 271: | Zeile 271: | ||
</code> | </code> | ||
- | ===== Branching Statements ===== | + | ==== Branching Statements ===== |
- | ==== Switch ==== | + | === Switch ==== |
<code java> | <code java> | ||
Zeile 306: | Zeile 306: | ||
</code> | </code> | ||
- | ===== Exceptions ===== | + | ==== Exceptions ===== |
- | ==== Important Classes ===== | + | === Important Classes ===== |
[[javaref>api/java/lang/Throwable.html]] | [[javaref>api/java/lang/Throwable.html]] | ||
Zeile 333: | Zeile 333: | ||
Developer: typically thrown by a Devoloper of an application or API | Developer: typically thrown by a Devoloper of an application or API | ||
- | ==== Facts ===== | + | === Facts ===== |
* It's ok for an overriding method to throw the same exceptions, narrower exceptions, no exceptions or any runtime exceptions | * It's ok for an overriding method to throw the same exceptions, narrower exceptions, no exceptions or any runtime exceptions | ||
Zeile 348: | Zeile 348: | ||
* Only allowed order try{...}catch(XXXExcption e){...}finally{...}, and no code in-between! | * Only allowed order try{...}catch(XXXExcption e){...}finally{...}, and no code in-between! | ||
- | ===== Assertions ===== | + | ==== Assertions ===== |
Principle: If an assertion expression evaluates to false, than an AssertionError is thrown if, and only if java is started with -ea flag | Principle: If an assertion expression evaluates to false, than an AssertionError is thrown if, and only if java is started with -ea flag | ||
Zeile 368: | Zeile 368: | ||
* VM evaluates all assertion flags left2right | * VM evaluates all assertion flags left2right | ||
- | ==== Compiler Issuses ==== | + | === Compiler Issuses ==== |
<code java> | <code java> | ||
int assert = 0;// warning with javac -source 1.3; error with -source 1.4 | int assert = 0;// warning with javac -source 1.3; error with -source 1.4 | ||
Zeile 374: | Zeile 374: | ||
</code> | </code> | ||
- | ====== 6. Strings, IO, Formatting and Parsing ====== | + | ===== 6. Strings, IO, Formatting and Parsing ====== |
- | ===== Strings ===== | + | ==== Strings ===== |
- | ==== Class String ===== | + | === Class String ===== |
Important public methods: | Important public methods: | ||
Zeile 400: | Zeile 400: | ||
* String is final => it can't be overwritten | * String is final => it can't be overwritten | ||
- | ==== Classes StringBuffer and StringBuilder ===== | + | === Classes StringBuffer and StringBuilder ===== |
Imporant public methods: | Imporant public methods: | ||
Zeile 419: | Zeile 419: | ||
* StringBuffer.equals is not overwritten and therefore useless! | * StringBuffer.equals is not overwritten and therefore useless! | ||
- | ===== File Navigation and IO ===== | + | ==== File Navigation and IO ===== |
- | ==== Metods of File ===== | + | === Metods of File ===== |
[[javaref>api/java/io/File.html]] | [[javaref>api/java/io/File.html]] | ||
Zeile 440: | Zeile 440: | ||
</code> | </code> | ||
- | ==== Serialization ===== | + | === Serialization ===== |
[[java#i_o_streams|IO stream overview]] | [[java#i_o_streams|IO stream overview]] | ||
Zeile 454: | Zeile 454: | ||
Static variables are //never// being serialized! | Static variables are //never// being serialized! | ||
- | === Manipulation of Serialization == | + | == Manipulation of Serialization == |
If a class to be serialized provides exactly | If a class to be serialized provides exactly | ||
Zeile 469: | Zeile 469: | ||
The order of the method calls on os and is has to be the same in both methods! | The order of the method calls on os and is has to be the same in both methods! | ||
- | === Inheritance and Serialization == | + | == Inheritance and Serialization == |
When objects are deserialized, no constructors are running. (It makes no sense because we want to resore the state before serializing, not the initial state) | When objects are deserialized, no constructors are running. (It makes no sense because we want to resore the state before serializing, not the initial state) | ||
Zeile 475: | Zeile 475: | ||
Serializable objects with non-serializable superclasses can be serialized, but the values inherited from the first non-serializable superclass and upward will //not// going to be restored. Instead the constructor of the first non-serializable superclass will be called and thus also every constructor ABOVE will run. | Serializable objects with non-serializable superclasses can be serialized, but the values inherited from the first non-serializable superclass and upward will //not// going to be restored. Instead the constructor of the first non-serializable superclass will be called and thus also every constructor ABOVE will run. | ||
- | === Serialized Arrays and Collections == | + | == Serialized Arrays and Collections == |
For serializing an array or collection, every element must be serializable. Otherwise, an exception is thrown :?: | For serializing an array or collection, every element must be serializable. Otherwise, an exception is thrown :?: | ||
Zeile 481: | Zeile 481: | ||
The collection interfaces are not serializable, but the concrete collection classes in the Java API are. This means, that the type of the reference variable to the collection must be of the concrete (implementing) class type, not of the interface type, like usually :?: | The collection interfaces are not serializable, but the concrete collection classes in the Java API are. This means, that the type of the reference variable to the collection must be of the concrete (implementing) class type, not of the interface type, like usually :?: | ||
- | ===== Dates, Numbers and Currencies == | + | ==== Dates, Numbers and Currencies == |
Only instances of the classes Date and Locale can be created with a constructor. For Calendar, DateFormat and NumberFormat factory methods must be used :!: | Only instances of the classes Date and Locale can be created with a constructor. For Calendar, DateFormat and NumberFormat factory methods must be used :!: | ||
- | ==== Class Date == | + | === Class Date == |
Most of Date is deprecated, but the followning uses and methods are useful: | Most of Date is deprecated, but the followning uses and methods are useful: | ||
Zeile 495: | Zeile 495: | ||
</code> | </code> | ||
- | ==== class Calendar == | + | === class Calendar == |
Useful methods and uses of class Calendar: | Useful methods and uses of class Calendar: | ||
Zeile 521: | Zeile 521: | ||
</code> | </code> | ||
- | ==== Class DateFormat == | + | === Class DateFormat == |
Class DateFormat isn't aware of a certain date (=point in time)? | Class DateFormat isn't aware of a certain date (=point in time)? | ||
Zeile 549: | Zeile 549: | ||
</code> | </code> | ||
- | ==== Class Locale == | + | === Class Locale == |
<code java> | <code java> | ||
Zeile 558: | Zeile 558: | ||
</code> | </code> | ||
- | ==== Class NumberFormat == | + | === Class NumberFormat == |
<code java> | <code java> | ||
Zeile 579: | Zeile 579: | ||
</code> | </code> | ||
- | ===== Parsing, Tokenizing and Formatting == | + | ==== Parsing, Tokenizing and Formatting == |
- | ==== Parsing == | + | === Parsing == |
In general regex serch runs from left to right and once a source's character has been used in a match, it cannot be reused. | In general regex serch runs from left to right and once a source's character has been used in a match, it cannot be reused. | ||
Zeile 615: | Zeile 615: | ||
th \ to get the literal meaning. But \ is also the escape char when defining strigs, so it must iself be escaped! = Any metachar in a search pattern that starts with \ has to be escaped in the string def, eg: pattern \w becomes ''String pattern="\\w"'' | th \ to get the literal meaning. But \ is also the escape char when defining strigs, so it must iself be escaped! = Any metachar in a search pattern that starts with \ has to be escaped in the string def, eg: pattern \w becomes ''String pattern="\\w"'' | ||
- | ==== Tokenizing == | + | === Tokenizing == |
<code java> | <code java> | ||
Zeile 628: | Zeile 628: | ||
- | ==== Formatting == | + | === Formatting == |
Format string is composed by: ''%[ArgIndex$][flags][width][.precision]conversionChar'' | Format string is composed by: ''%[ArgIndex$][flags][width][.precision]conversionChar'' | ||
Zeile 652: | Zeile 652: | ||
Formatting is available for ''String.format()''; ''PrintStream.printf()'' = ''PrintStream.format()'' and '''' (and more?), [[javaref>api/java/util/Formatter.html#syntax|more]] --- 2007-05-03 | Formatting is available for ''String.format()''; ''PrintStream.printf()'' = ''PrintStream.format()'' and '''' (and more?), [[javaref>api/java/util/Formatter.html#syntax|more]] --- 2007-05-03 | ||
- | ===== Math class ===== | + | ==== Math class ===== |
INO Not tested any more | INO Not tested any more | ||
* represents a library -> only static methods, private constructor, is a final class | * represents a library -> only static methods, private constructor, is a final class | ||
Zeile 670: | Zeile 670: | ||
* (Double.NaN == Double.NaN) is always false! | * (Double.NaN == Double.NaN) is always false! | ||
- | ===== Wrapper Classes ===== | + | ==== Wrapper Classes ===== |
* equals method is properly overridden | * equals method is properly overridden | ||
* wrapped values cannot be modified, wrapper classes are immutable (like String) | * wrapped values cannot be modified, wrapper classes are immutable (like String) | ||
Zeile 681: | Zeile 681: | ||
| ''Wrapper.valueOf(String)'' | string → wrapper | IYES | all 6 number Wrappers + Boolean | | | ''Wrapper.valueOf(String)'' | string → wrapper | IYES | all 6 number Wrappers + Boolean | | ||
- | ===== Using equals(Object) ===== | + | ==== Using equals(Object) ===== |
* If equals() is overwritten, also hashcode() hast to be overwritten, because equal objects should have the same hash code | * If equals() is overwritten, also hashcode() hast to be overwritten, because equal objects should have the same hash code | ||
* equals() for wrapper classes returns only true if | * equals() for wrapper classes returns only true if | ||
Zeile 688: | Zeile 688: | ||
* equals() of StringBuffer is **not** overwritten => 2 StringBuffer objects cannot be compared like strncmp() | * equals() of StringBuffer is **not** overwritten => 2 StringBuffer objects cannot be compared like strncmp() | ||
- | ====== 7. Generics and Collections == | + | ===== 7. Generics and Collections == |
- | ===== Overriding hashCode() and equals() ===== | + | ==== Overriding hashCode() and equals() ===== |
Zeile 709: | Zeile 709: | ||
Wrapper Classes like Integer also do a type check within their equals methods. Called with eg. a long leads to Long via autoboxing and thus the comparison always fails, regardless of the value. | Wrapper Classes like Integer also do a type check within their equals methods. Called with eg. a long leads to Long via autoboxing and thus the comparison always fails, regardless of the value. | ||
- | ===== Collections ===== | + | ==== Collections ===== |
- | [[javatut>reallybigindex.html#collections|Chapter in the Java tutorial]] | + | See [[java#Collections]] |
- | | //[[javaref>api/java/util/Collection.html|Collection]]// |||| //[[javaref>api/java/util/Map.html|Map]]// || | + | |
- | | //[[javaref>api/java/util/Set.html|Set]]// || //[[javaref>api/java/util/List.html|List]]// | //[[javaref>api/java/util/Queue.html|Queue]]// | || | + | |
- | | | //[[javaref>api/java/util/SortedSet.html|SortedSet]]// | | | | //[[javaref>api/java/util/SortedMap.html|SortedMap]]// | | + | |
- | | HashSet LinkedHashSet | TreeSet | LinkedList Vector ArrayList | LinkedList, PriorityQueue | HashTable LinkedHashMap HashMap | TreeMap | | + | |
- | <code java> | + | ==== Generics ===== |
- | // important methods of List: | + | |
- | boolean add(E e) | + | |
- | void add(int index, E element) | + | |
- | boolean contains(Object o) | + | |
- | E get(int index) | + | |
- | int indexOf(Object o) | + | |
- | Iterator<E> iterator() | + | |
- | E remove(int index) | + | |
- | boolean remove(Object o) // Removes the first occurrence | + | |
- | Object[] toArray() | + | |
- | <T> T[] toArray(T[] a) | + | |
- | + | ||
- | // important methods of Map | + | |
- | boolean containsKey(Object key) | + | |
- | boolean containsValue(Object value) | + | |
- | V get(Object key) | + | |
- | Set<K> keySet() // Returns a set of the keys | + | |
- | V put(K key, V value) // there is no add! | + | |
- | V remove(Object key) | + | |
- | + | ||
- | // important methods of Queue: | + | |
- | boolean offer(E o) // Inserts the specified element at the end; also add() possible | + | |
- | E peek() // Retrieves, but does not remove, | + | |
- | E poll() // Retrieves and removes from the beginning; remove() also possible | + | |
- | </code> | + | |
- | + | ||
- | * Set: has no special order and no duplicates are permitted, not indexed; methods ar a subset of List (no index operations) | + | |
- | * List: ordered, duplicates are permitted, indexed | + | |
- | * Map does not implement the collection interface | + | |
- | * 'Sorted' is a subset of 'Ordered' | + | |
- | * Ordering: | + | |
- | * //Lists// are always ordered by index | + | |
- | * //Linked// collections are always ordered by insertion or last access | + | |
- | * //Tree// collections are always sorted | + | |
- | * List can made thread-save by Collections.synchronizedList() | + | |
- | * Tutorial: Vector is a legacy class; API: Vector is a normal class; Hashtable is similar; Vector also implements List | + | |
- | * HashSet & LinkedHashSet: Overwrite hashCode() so that equal objects provide the same hashcode | + | |
- | * LinkedList implements //List// and //Queue// | + | |
- | * //Queue// has Fifo (not stack) behaviour! | + | |
- | * All Interfaces have a size() method | + | |
- | * PriorityQueue sorts Elements by natural order using Comparable | + | |
- | * Elements for SortedSet/TreeSet, SortedMap/TreeMap | + | |
- | + | ||
- | PriorityQueue must implement the Comparable interface! | + | |
- | * String implements interface Comparable<String> and Integer implements Comparable<Integer> -> Trying to add both Types to any untyped (old style) Tree-Container results in a ClassCastException | + | |
- | * Whereas adding only the same Type (eg Strings) works but gives a compiler warning. (I assume the type is detected at run time by reflection and the Object to compare is casted to String before compareTo() is called.) | + | |
- | + | ||
- | ==== Sorting and Searching == | + | |
- | === Sorting with the Comparable Interface == | + | |
- | + | ||
- | To sort a //List// (eg ArrayList) or an array use: | + | |
- | <code java> | + | |
- | static void Collections.sort(List<T> list); | + | |
- | static void Arrays.sort(allPrimitivesAndObject[] a); | + | |
- | </code> | + | |
- | The List interface has no sort method! All elements in the List or array must implement the Comparable interface: | + | |
- | + | ||
- | <code java> | + | |
- | Interface Comparable<T> { | + | |
- | int compareTo(T o); | + | |
- | } | + | |
- | </code> | + | |
- | Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. Keep in mind that compareTo accepts Type T (the generic of the List) wheras equals always only accepts type Object! | + | |
- | + | ||
- | === Sorting with the Comparator Interface == | + | |
- | + | ||
- | <code java> | + | |
- | static void Collections.sort(List<T> list, Comparator<? super T> c); | + | |
- | static void Arrays.sort(T[] a, Comparator<? super T> c); // T is an Object, no primitives! | + | |
- | + | ||
- | Interface Comparator<T> { | + | |
- | int compare(T o1, T o2); | + | |
- | } | + | |
- | </code> | + | |
- | + | ||
- | === Searching == | + | |
- | + | ||
- | <code java> | + | |
- | static int Collections.binarySearch(List<T> list, T key[, Comparator<? super T> c]); | + | |
- | static int Arrays.binarySearch(allPrimitivesAndObject[] a, allPrimitivesAndObject key); | + | |
- | static int Arrays.binarySearch(T[] a, T key, Comparator<? super T> c); | + | |
- | </code> | + | |
- | Call binarySearch() with the array or List as first param, the key as second, and, if not all items implement the Comparable interface, provide a Comparator as 3rd parameter. List or array has to be sorted before binarySearch can be called, otherwise the result is not predictable! If the element is not found, binarySearch returns -length-1 | + | |
- | + | ||
- | ===== Generics ===== | + | |
Autoboxing works where a primitive is supplied and an Object is expected, whereas unboxing doesn't work where an Object is supplied and a primitive is expected. -> The upcast to eg Integer must be done by hand: | Autoboxing works where a primitive is supplied and an Object is expected, whereas unboxing doesn't work where an Object is supplied and a primitive is expected. -> The upcast to eg Integer must be done by hand: | ||
Zeile 833: | Zeile 744: | ||
</code> | </code> | ||
- | ===== Garbage Collection ===== | + | ==== Garbage Collection ===== |
* Handle eines Objekts kann auf null gesetzt werden, damit die GC sicher zuschlagen kann | * Handle eines Objekts kann auf null gesetzt werden, damit die GC sicher zuschlagen kann | ||
Zeile 841: | Zeile 752: | ||
* For every object finalize() is called at most once | * For every object finalize() is called at most once | ||
- | ====== 8. Inner Classes ===== | + | ===== 8. Inner Classes ===== |
See [[java#inner_classes|overview]] first! | See [[java#inner_classes|overview]] first! | ||
- | ===== (Regular) Inner Class ===== | + | ==== (Regular) Inner Class ===== |
* Instantiating an inner class requires an instance of the outer class. | * Instantiating an inner class requires an instance of the outer class. | ||
* Can use both class and instance variables of the outer class | * Can use both class and instance variables of the outer class | ||
Zeile 852: | Zeile 763: | ||
* Allowed modifiers: final, abstract, public, private, protected, static, strictfp | * Allowed modifiers: final, abstract, public, private, protected, static, strictfp | ||
- | ===== Method-local inner Class ===== | + | ==== Method-local inner Class ===== |
* Can be instanitated only within the method where it is defined | * Can be instanitated only within the method where it is defined | ||
* object of MLIC can only use //final// local variables of the method | * object of MLIC can only use //final// local variables of the method | ||
Zeile 859: | Zeile 770: | ||
* If declared in a static method it has only access to the static members of the enclosing class | * If declared in a static method it has only access to the static members of the enclosing class | ||
- | ===== Anonymous inner Class ===== | + | ==== Anonymous inner Class ===== |
* AIC's are created on the fly by implementing the mehtods of an interface or inheriting form another class (and overwirting methods) | * AIC's are created on the fly by implementing the mehtods of an interface or inheriting form another class (and overwirting methods) | ||
* Watch for missing semicolons after the AIC ends! | * Watch for missing semicolons after the AIC ends! | ||
Zeile 867: | Zeile 778: | ||
- | ===== Static nested Class ===== | + | ==== Static nested Class ===== |
* More a concept of name-space scope | * More a concept of name-space scope | ||
* Is a class that's a static member of the enclosing class => it can be accessed without an instance of the outer class | * Is a class that's a static member of the enclosing class => it can be accessed without an instance of the outer class | ||
Zeile 874: | Zeile 785: | ||
* ICs that are declared static automatically become top level classes | * ICs that are declared static automatically become top level classes | ||
- | ====== 9 Threads ====== | + | ===== 9 Threads ====== |
See [[java#Threads|java>Threads]] first | See [[java#Threads|java>Threads]] first | ||
- | ===== General ===== | + | ==== General ===== |
* ''Thread'' implements ''//Runnable//'' which defines the single method ''public void run()'' | * ''Thread'' implements ''//Runnable//'' which defines the single method ''public void run()'' | ||
Zeile 885: | Zeile 796: | ||
* static's sleep() & join() (of Thread) & wait() of Object all throw InterruptedException, but not static yield() (of Thread) | * static's sleep() & join() (of Thread) & wait() of Object all throw InterruptedException, but not static yield() (of Thread) | ||
- | ===== Synchronized ===== | + | ==== Synchronized ===== |
* syncronized method or code block: Only one thread can access the code at one time | * syncronized method or code block: Only one thread can access the code at one time | ||
Zeile 897: | Zeile 808: | ||
* Threads running static synchronized methods own the lock of the Class object of the class. Access: ''SomeClass.class'' or ''someObject.getClass()''. See [[javatut>reflect/class/getClass.html]]. | * Threads running static synchronized methods own the lock of the Class object of the class. Access: ''SomeClass.class'' or ''someObject.getClass()''. See [[javatut>reflect/class/getClass.html]]. | ||
- | ====== 10. Development ====== | + | ===== 10. Development ====== |
- | ===== javac ====== | + | ==== javac ====== |
-d specifies the target dir for the generated class files. Specifying a nonexistent dir generates a compiler error. | -d specifies the target dir for the generated class files. Specifying a nonexistent dir generates a compiler error. | ||
Zeile 906: | Zeile 817: | ||
If ''-d'' is //not// specified and source file starts with a package statement, the class files will be generated in the dir where the source file is located. This is usually the current dir, but not necessarily. | If ''-d'' is //not// specified and source file starts with a package statement, the class files will be generated in the dir where the source file is located. This is usually the current dir, but not necessarily. | ||
- | ===== java ====== | + | ==== java ====== |
''java -DmyProp=Willi SomeClass'' adds the key/value pair to the system properties. No space between -D and key is allowed. Get sysprops with: | ''java -DmyProp=Willi SomeClass'' adds the key/value pair to the system properties. No space between -D and key is allowed. Get sysprops with: | ||
Zeile 921: | Zeile 832: | ||
The -D flag in not a compiler flag, it works only with java, not javac! | The -D flag in not a compiler flag, it works only with java, not javac! | ||
- | ===== classpath ====== | + | ==== classpath ====== |
Search order: First system default classes than classpath content. cp can be an environment variable. But if -cp is specified, the environment variable will be ignored. Searching goes from left to right. It stops as soon, as a class is found. | Search order: First system default classes than classpath content. cp can be an environment variable. But if -cp is specified, the environment variable will be ignored. Searching goes from left to right. It stops as soon, as a class is found. | ||
Zeile 929: | Zeile 840: | ||
In order to compile A.java which needs B.java, both of package mp; javac has to be invoked with the parent dir of mp in the classpath! Reason: A.java uses class B without additional qualifier. This means that B is searched in the same package mp which must be a subdir of the dir's in classpath. | In order to compile A.java which needs B.java, both of package mp; javac has to be invoked with the parent dir of mp in the classpath! Reason: A.java uses class B without additional qualifier. This means that B is searched in the same package mp which must be a subdir of the dir's in classpath. | ||
- | ===== Jar Files ====== | + | ==== Jar Files ====== |
* have to be specified at the end of the classpath? | * have to be specified at the end of the classpath? | ||
Zeile 937: | Zeile 848: | ||
* The dir tree inside the jar file usually resembles the package structure ie the import statements | * The dir tree inside the jar file usually resembles the package structure ie the import statements | ||
- | ===== Import static ====== | + | ==== Import static ====== |
* Statement is ''import static'' not vice versa! | * Statement is ''import static'' not vice versa! | ||
Zeile 966: | Zeile 877: | ||
- Wildcard import of 2 statics with the same name, and trying to use the name results in a compiler error | - Wildcard import of 2 statics with the same name, and trying to use the name results in a compiler error | ||
- | ====== Meta ====== | + | ===== Meta ====== |
- | ===== toDo ===== | + | ==== toDo ===== |
* Repeat failed tests (also old 1.4 ones) | * Repeat failed tests (also old 1.4 ones) | ||
Zeile 977: | Zeile 888: | ||
* Do Mock Test at http://www.javacamp.org | * Do Mock Test at http://www.javacamp.org | ||
- | ===== nimmit ===== | + | ==== nimmit ===== |
* Wasser | * Wasser | ||
Zeile 984: | Zeile 895: | ||
* Papier, weiß, geheftet | * Papier, weiß, geheftet | ||
- | ===== Failed Tests ===== | + | ==== Failed Tests ===== |
- | ==== scjp 1.4 Book ==== | + | === scjp 1.4 Book ==== |
* chap1 | * chap1 | ||
Zeile 1005: | Zeile 916: | ||
* chap9 Threads | * chap9 Threads | ||
- | ==== scjp 5 Book ==== | + | === scjp 5 Book ==== |
* chap05 | * chap05 | ||
Zeile 1018: | Zeile 929: | ||
* 2006-09-24: 1 2 (Q10 is wrong in the book) | * 2006-09-24: 1 2 (Q10 is wrong in the book) | ||
- | ===== Links ===== | + | ==== Links ===== |
* [[http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=next_topic&f=24&t=034229&go=newer|scjp5 book errata]] | * [[http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=next_topic&f=24&t=034229&go=newer|scjp5 book errata]] |