JavaAPI
Collections[edit]
Seit Java 1.2 gibt es das Collection API. Seitdem gibt es die Interfaces sowie die entsprechenden implementations:
- Collection
- List (LinkedList, ArrayList, Vector, Stack)
- Set (HashSet, TreeSet)
- Map (HashMap, LinkedHashMap, TreeMap)
Traversing[edit]
extended for[edit]
s. extended for
Iterators/Enumerations[edit]
Für Iteratoren definiert die Java-Bibliothek zwei unterschiedliche Schnittstellen. Das hat historische Gründe. Die Schnittstelle Enumeration gibt es seit den ersten Java-Tagen; die Schnittstelle Iterator gibt es seit Java 1.2, seit der Collection-API. Der Typ Iterator ist jedoch deutlich weiter verbreitet. Beiden Schnittstellen ist eine Funktion gemeinsam, die das nächste Element erfragt, und eine Funktion, die ermittelt, ob es überhaupt ein nächstes Element gibt. So wandert der Iterator einen Datengeber (in der Regel eine Datenstruktur) Element für Element ab. Die Namen der Operationen unterscheiden sich in den Schnittstellen ein wenig und sind beim Iterator kürzer.
for (java.util.Iterator<Type> i = o.getCollection().iterator();ii.hasNext();)
{
Type t = ii.next();
}
Die Schnittstelle Iterator bietet eine Möglichkeit, die Enumeration nicht bietet. Das zuletzt aufgezählte Element lässt sich aus dem zugrunde liegenden Container mit remove() entfernen. Vor dem Aufruf muss jedoch next() das zu löschende Element als Ergebnis geliefert haben. Eine Enumeration kann die aufgezählte Datenstruktur grundsätzlich nicht verändern. Sie stellt quasi eine Pointer-Liste darstellen und es aus diesem Grund gefährlich ist, die Quelle zu modifizieren, während man interiert. In der Regel löst dies eine ConcurrentModificationException aus.
import java.util.Enumeration; for (Enumeration e = ds.elements(); e.hasMoreElements();) System.out.println(e.nextElement());
ArrayList[edit]
dynamic linear (ordered) list, index starts with 0
add(<Element>)adds elements to the end of the list
Bitsets[edit]
Collection[edit]
The Collection interface is used to pass around collections of objects where maximum generality is desired. For traversing see Traversing.
HashSet[edit]
unordered set of elements with no doublettes
Hashtable[edit]
associative memory
LinkedList[edit]
doubled chained list
List[edit]
import java.util.List; List<C> l = new ArrayList<C>(); C c = l.get(0); // 0-based index
Map[edit]
import java.util.Map;
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value.
Properties[edit]
specialized hashtable for strings
Queues[edit]
Stack[edit]
LIFO principle
TreeSet[edit]
like HashSet but ordered
Vector[edit]
The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.
v = new java.util.Vector();
v.add("xyz");
for (java.util.Enumeration e = v.elements();
e hasMoreElements();)
{
e.nextElement();
}
Date and Time[edit]
java.util.Date[edit]
The class Date represents a specific instant in time, with millisecond precision. The Date class is intended to reflect coordinated universal time (UTC). In all methods of class Date that accept or return year, month, date, hours, minutes, and seconds values, the following representations are used:
- A year y is represented by the integer y - 1900.
- A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.
- A date (day of month) is represented by an integer from 1 to 31 in the usual manner.
- An hour is represented by an integer from 0 to 23. Thus, the hour from midnight to 1 a.m. is hour 0, and the hour from noon to 1 p.m. is hour 12.
- A minute is represented by an integer from 0 to 59 in the usual manner.
- A second is represented by an integer from 0 to 61; the values 60 and 61 occur only for leap seconds and even then only in Java implementations that actually track leap seconds correctly. Because of the manner in which leap seconds are currently introduced, it is extremely unlikely that two leap seconds will occur in the same minute, but this specification follows the date and time conventions for ISO C.
Environment[edit]
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
return_text += envName + " " + env.get(envName);
}
Serialization[edit]
When deserializing an object of class X, Java must establish that the incoming data is sufficiently compatible with the local class X definition. This is accomplished by comparing the so-called stream-unique identifiers (SUIDs) of the incoming and local class definitions. If the two SUIDs do not match, deserialization fails. If you don't do anything, that is manually add and maintain an attribute
public static final long serialVersionUID = 3L
to your class, the SUID is computed as a hash of various class elements: class name, implemented interfaces, declared nonstatic, nontransient fields, declared nonprivate methods, and so on.
Logging[edit]
import java.util.logging.*;
Logging can be configured in three different ways: you can supply a properties file that describes the logging setup (by default this is called logging.properties and lives in JRE/lib/ or you specify it by startup s. command line parameters). Die Log Levels in absteigender Ordnung sind:
- SEVERE (höchste Dringlichkeit)
- WARNING
- INFO
- CONFIG
- FINE
- FINER
- FINEST (niedrigste Dringlichkeit)
Zusätzlich gibt es noch die Level OFF und ALL, um das Logging auszuschalten bzw. jede Meldung zu loggen.
Multi-Threading Support[edit]
Im java.lang package existiert die Klasse Thread. Threads can be in one of four states:
- new
- runnable
- blocked
- dead
Ein Thread ist entweder ein User-Thread oder ein Daemon-Thread, wobei erstere das Beenden der JVM verhindern. Alle Objekte, die in einem Thread laufen sollen, müssen das Interface Runnable implementieren, das als einzige Methode run() enthält. Dieses implentierende Objekt wird einem Thread-Objekt im ctor übergeben und dann dessen start()-Methode aufgerufen. Eine Alternative ist die Klasse Thread zu spezialisieren, hat aber den Nachteil, daß diese Klasse von Thread erben muß, somit nicht von anderen Klassen erben kann und die Funktionalität nicht unbedingt erweitert. Daher ist die Realisierung mit dem Runnable Interface zu bevorzugen. Das Erzeugen eines Threads ist eine sehr aufwendige Angelegenheit, daher ist eine Thread-Pooling Lösung anzustreben.First methods can be declared as synchronized (see 1.11.11.2). Additionally java provides the synchronized statement to protect critical section by
synchronized (<expression>) <statements>
<expression> is an expression the must resolve to an object or an array. The synchronized statement attempts to acquire an exclusive lock for the object or array und garantiert, dass nur ein Thread auf das Objekt zugreift. Synchronität wird durch ein lock auch monitor genannt, daß für jedes java object und für jedes java class object existiert, verwaltet wird. Angeblich ist die Synchronisation über Methoden etwas schneller als über blocks. Die class Synchronisation kann auch durch \\ synchronized (<ClassName>.class) <statements>
erreicht werden. Beim Zugriff auf static variables ist besondere Vorsicht geboten, da es durchaus möglich ist, daß zwei Instanzen, die in unterschiedlichen Threads verwendet werden, auf diese eine statische Variable zugreifen. Deshalb gibt es ein per-class lock, der wiederum nur static Methoden lockt.
Außerdem besitzt die Klasse java.lang.Object die Methoden wait(), notify() und notifyAll().
Timer[edit]
import java.util.Timer;
import java.util.TimerTask;
class MyTask extends TimerTask
{
public void run()
{
...
}
}
Timer t = new Timer();
t.schedule(new MyTask());
For every Timer there is a thread, which executes the tasks.
API Classes[edit]
Class ‘Class’[edit]
Java always maintains what is called run-time type information. You can access this information by working with the class Class and calling <Object>.getClass() or by <Object>.class. The class Class contains the following methods:
| forName(String ClassName) | ||
| Method getDeclaredMethod( |
<MethodName>,\\\\<ArrayOfArgumentClasses>)|{| border=1 cellpadding=2 cellspacing=0 |-
| |getInterface() | |-
| |getName() | |-
| |getSuperClass() | |-
| |isArray() | |-
| | | |-
| |newInstance() |this calls only the default ctor |-
| |isInterface() | |-
| |toString() | |} Interfaces are also stored in Class objects.
An object can also be created by a call to the newlnstance method of class Class, which performs these steps:
- A new object is created of the type represented by the class object for which the newlnstance method was invoked. As the new object is created, all its instance variables are initialized to their standard default values (§ Standard Default Values).
- The constructor for the newly created object is invoked with no actual arguments.
- After the constructor has returned, a reference to the newly created and initialized object is returned as the value of the call to the newlnstance method. The compile-time type of this reference will be Object, which is the declared return type of the newlnstance method, but its run-time type will be the type represented by the class object for which the newlnstance method was invoked.
Class 'Exception[edit]
- getMessage()
Class ‘Object’[edit]
Every java class extends Object but you don’t have to write
class <ClassName> extends Object
Your classes may want to override the following Object methods:
| protected clone() | The JVM requires classes to implement the java.lang.Cloneable interface to explicitly declare an object to have the capability to be cloned. The Object.clone() method will create a shallow copy of the current object, that is only the primitives and reference values are copied, so sharing all referenced objects. Um ein Objekt zu kreieren sollte nie ein ctor verwendet werden sondern super.clone() (s. [24] page 70). |
| equals(Object o) | This method checks if some other object passed to it as an argument is equal to the object on which this method is invoked. In der Standardimplementierung von Object wird nur verglichen ob zwei zu vergleichende Objektereferenzen auf das gleiche physikalische Objekt zeigen, d.h. if a == b. This particular comparison is also known as "shallow comparison". The classes providing their own implementations of the equals method are supposed to perform a "deep comparison". The JDK 1.4 says the implementation must be reflexive, symmetric, transitive and consistent.
The overwritten method must have a parameter of type object, otherwise it's overloading, not overwriting. |
| finalize() | |
| getClass() | |
| hashCode() | This method returns the hash code value for the object on which this method is invoked. This method returns the hash code value as an integer and is supported for the benefit of hashing based collection classes such as Hashtable, HashMap, HashSet etc. This method must be overridden in every class that overrides the equals method. Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes. |
| final notify() | removes one thread by random from the waiting list of this object. |
| final notifyAll() | removes all threads waiting for this object from the waiting list |
| String toString() | |
| wait() | calling wait() causes the thread to release control of the object's lock, which means that other threads are able to obtain the monitor for this object. |
Class String, StringBuffer, StringTokenizer[edit]
Class ‘Thread’[edit]
The Thread class has the following operations:
| interrupt() | |
| isalive() | |
| join() | waits for the specified thread to cease to be alive or for the specified amount of milliseconds |
| run() | is executed when the thread is running; override this operation to perform your task |
| static void sleep(Millis) | puts the currently executing thread to sleep for the specified Time. |
| start() | the run method will be called; returns immediately |
| stop() | kills the thread |
| yield() | aufgeben, abtreten |
Array Helper[edit]
java.util.Array
Class ‘Runtime’[edit]
Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the static Runtime.getRuntime() method. Über die Runtime-Instanz kann dann beispielsweise eine andere Applikation aufgerufen werden: Process p = rt.exec("C:\\Programme\\Microsoft Office\\Office\\winword.exe");
Class 'URL'[edit]
java.net.URL url = new URL(<URLString>); Object c = url.getContent();
getContent() returns an object of a class depending on content:
- java.awt.Image in case of GIF, JPEG and PNG
- java.applet.AudioClip in case of WAV, ...
- java.io.InputStream or sub-classes like HttpInputStream