JavaAPI

From Wiki RB4

Collections

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, TreeMap)

Iterators/Enumerations

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());

Bitsets

Hashtable

associative memory

Properties

specialized hashtable for strings

HashSet

unordered set of elements with no doublettes

TreeSet

like HashSet but ordered

ArrayList

dynamic linear list

LinkedList

doubled chained list

Queues

Vector

represents a linear list of arbitrary type

Stack

LIFO principle


Vector

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();
}


Multi-Threading Support

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().

Class ‘Object’

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\\\\native 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 in der Standardimplementierung von Object wird nur verglichen ob zwei zu vergleichende Objektereferenzen auf das gleiche physikalische Objekt zeigen, d.h. if a == b.
finalize
getClass
hashCode wird im Zusammenhang mit Hashtable class verwendet. Damit ein Objekt korrekt in einer Hashtable verwaltet werden kann, muß dieses Objekt die equals() und hashCode() Methode überschreiben.
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 ‘Class’

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 String, StringBuffer, StringTokenizer

Class ‘Thread’

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

Class ‘Runtime’

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");