Index
Crashkurs Java im Modul Algorithmen und Datenstrukturen
public class Main {
public static void main(String[] args) {
System.out.println("Die Seite ist noch leer");
}
}
01: Hello World
Approach 1: Simple String Output
// main.java
public class main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
>> javac main.java
>> java main
Hello, World!
Was sagt dieser Code nun aus?
* Eine Klasse "main" ist öffentlich
* Dem Compiler wird die statische Methode main
vorlegt
* Diese wird bei jedem Java Code genutzt
* Wir rufen die Klasse System auf und führen einen println
-Befehl aus
* Hello, World!
wird in der Konsole ausgegeben
Approach 2: Using Console Arguments
// main.java
public class main {
public static void main(String[] args) {
System.out.println(args[0] + " " + args[1]);
}
}
>> javac main.java
>> java main Hello, World!
Hello, World!
Was ist nun anders?
* Die Main-Methode übergibt standardmäßig Konsolenargumente als Array vom Typ String mit dem Namen args
* Jedes Argument hat einen Index im Array
* Für 2 Argumente rufen wir die ersten zwei Indexes auf, beginnend bei 0
02: Basics
Table of Contents
- Nutzung der Konsole
- Primitive Datentypen
- Nicht Primitive Datentypen
- Operatoren
- Bedingungen
- Schleifen
- Exceptions
Nutzung der Konsole
Ausgabe
System.out.println("print me and create a new line");
System.out.println(); // prints nothing but creates new line afterwards
System.out.print("print me without a new line | ");
System.out.print("print me but add a new line \n");
System.out.print("yeah, this is on the new line! \n");
System.out.println(); // prints nothing but creates new line afterwards
// https://www.digitalocean.com/community/tutorials/java-printf-method
System.out.printf("%s %s \n", "parameter 1", "parameter 2");
System.out.printf("%s %e %f", "10.50", 10.50, 10.50);
Eingabe
import java.util.Scanner;
// class and method : start
Scanner myScanner = new Scanner(System.in);
System.out.print("Enter Username: ");
String username = myScanner.nextLine();
System.out.print("Enter Password: ");
String password = myScanner.nextLine();
System.out.println("your Username: " + username + "\nyour password: " + password );
// class and method : end
Primitive Datentypen
Quelle: w3schools.com
Data Type | Size | Description |
---|---|---|
byte | 1 byte | Stores whole numbers from -128 to 127 |
short | 2 bytes | Stores whole numbers from -32,768 to 32,767 |
int | 4 bytes | Stores whole numbers from -2,147,483,648 to 2,147,483,647 |
long | 8 bytes | Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
float | 4 bytes | Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits |
double | 8 bytes | Stores fractional numbers. Sufficient for storing 15 decimal digits |
boolean | 1 bit | Stores true or false values |
char | 2 bytes | Stores a single character/letter or ASCII values |
Type Casting
Bei Type Casting handelt es sich um das überführen eines primitiven Datentypen in einen anderen.
Quelle: w3schools.com
Widening Casting (automatically)
Hier wird ein kleinerer Typ in einen größeren Typ konvertiert
byte
-> short
-> char
-> int
-> long
-> float
-> double
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
Narrowing Casting (manually)
Hier wird ein größerer Typ in einen kleineren Typ konvertiert
double
-> float
-> long
-> int
-> char
-> short
-> byte
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
Nicht Primitive Datentypen
String
String ist eine Wrapperklasse, welche eine Zeichenkette aus einzelnen chars zusammenbaut. In manchen Programmiersprachen (z.B. C++) ist ein String vergleichbar mit einem char-Array.
String myString = "this is a text";
System.out.println("myString: " + myString);
String concatString = "hello" + "World";
System.out.println("concatString: " + concatString);
Methoden der Standardbibliothek:
Methode | Beschreibung |
---|---|
myString.charAt() | Returns the char value at the specified index. |
myString.indexOf() | Returns the index within this string of the first occurrence of the specified substring. |
myString.substring() | Returns a string that is a substring of this string. |
myString.equals() | Compares this string to the specified object. |
myString.toLowerCase() | Converts all of the characters in this String to lower case. |
myString.toUpperCase() | Converts all of the characters in this String to upper case. |
myString.contains() | Returns true if and only if this string contains the specified sequence of char values. |
myString.replaceAll() | Replaces each substring of this string that matches the given regular expression with the given replacement. |
myString.compareTo() | Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. |
Numeric Datatypes
Im Gegensatz zu den primitiven Datentypen werden hier "Wrapper" verwendet, um dynamisch mit den Werten arbeiten zu können. Das erlaubt auch die Erweiterung um verschiedene Methoden in der Standardbibliothek.
Integer:
Integer myNumber = 10;
Integer.parseInt(); // Parses the string argument as a signed decimal integer.
Integer.parseUnsignedInt(); // Parses the string argument as an unsigned decimal integer.
Integer.valueOf(); // Returns an Integer object holding the value of the specified String.
Float and Double:
Double myDouble = 10.0;
myDouble.isNaN(); // Returns true if this Double value is a Not-a-Number (NaN), false otherwise.
Float myFloat = (float)10.0;
myFloat.isNaN(); // Returns true if this Float value is a Not-a-Number (NaN), false otherwise
Funktionen für alle Numerischen Datentypen (Nicht Primitiv):
Methode | Beschreibung |
---|---|
myNumber.compareTo() | Compares two Integer objects numerically. |
myNumber.toString() | Returns a String object representing this Integer's value. |
myNumber.intValue() | Returns the value of this Integer as an int. |
myNumber.floatValue() | Returns the value of this Integer as a float after a widening primitive conversion. |
myNumber.doubleValue() | Returns the value of this Integer as a double after a widening primitive conversion. |
myNumber.shortValue() | Returns the value of this Integer as a short after a narrowing primitive conversion. |
Arrays
Bei Arrays handelt es sich um Schleifen eines bestimmten Datentypen. Sie werden verwendet, um mehrere Werte in einer Variable zu speichern.
String[] myStringArray = new String[3];
myStringArray[0] = "ROT";
myStringArray[1] = "GRÜN";
myStringArray[2] = "BLAU";
int[] myIntArray = {0,1,2};
System.out.println(myIntArray.length); // 3
System.out.println(Arrays.toString(myIntArray)); // [0,1,2]
multidimensionale Arrays:
int[][] my2DArray = {
{1, 2},
{3, 4, 5},
{6, 7, 8, 9},
};
System.out.println(my2DArray.length);
System.out.println(my2DArray[0].length);
for(int row = 0; row < my2DArray.length; row++) {
System.out.print("[");
for(int column = 0; column < my2DArray[row].length; column++) {
if (column == (my2DArray[row].length - 1) ) {
System.out.print(my2DArray[row][column]);
continue;
}
System.out.print(my2DArray[row][column] + ", ");
}
System.out.println("]");
}
Methoden:
Methode | Beschreibung |
---|---|
Arrays.toString(Array a) | a string representation of the object. |
Arrays.copyOf(Array a, int index) | Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length. |
Arrays.compare(Array a, Array b) | Compares two int arrays lexicographically. |
Arrays.equals(Array a, Array b) | Returns true if the two specified arrays of ints are equal to one another. |
Arrays.sort(Array a) | Sorts the specified array into ascending numerical order |
Arrays.fill(Array a, int number) | Assigns the specified int value to each element of the specified array of ints. |
Operatoren
Arithmetic Operators
int calcAddition = 20 + 10; // = 30
int calcSubstraction = 20 - 10; // = 10
int calcMultiplication = 20 * 10; // = 200
int calcDivision = 20 / 10; // = 2
int calcModulus = 20 % 3; // = 2
int myNumber = 10;
myNumber++; // myNumber = 11
myNumber--; // myNumber = 10
myNumber--; // myNumber = 9
Comparison Operators
int biggerNumber = 20;
int biggerNumberAgain = 20;
int smallerNumber = 10;
// (20 == 20) => true
// (20 != 20) => false
// (20 > 10) => true
// (20 < 10) => false
// (20 >= 10) => true
// (20 >= 10) => true
Bedingungen
wir verwenden folgende Variablen:
int biggerNumber = 20;
int biggerNumberAgain = 20;
int smallerNumber = 10;
if-condition (better version)
if (biggerNumber > smallerNumber) {
System.out.println("the left number is bigger!");
}
if-condition (worse version)
// prefer to not write it down like this!
if (biggerNumber == biggerNumberAgain)
System.out.println("We don't do this here...");
if-else-condition
if (biggerNumber < smallerNumber) {
System.out.println("the left number is smaller!");
} else if (biggerNumber < biggerNumberAgain) {
System.out.println("but this time, the left number is smaller!");
} else {
System.out.println("the left number is just too big!");
}
switch-case
int luckyNumber = 69;
switch (luckyNumber) {
case 13:
System.out.println("some people consider 13 to be a lucky number");
break; // we need this to avoid default!
case 7:
System.out.println("slot machines value this number high");
break; // we need this to avoid default!
default:
System.out.println("seems, your number was not lucky enough...");
}
Schleifen
while-loop
int whileNumber = 3;
while (whileNumber > 0) {
System.out.println(whileNumber);
whileNumber --;
}
do-while-loop
System.out.println("--- doWhileNumber:");
int doWhileNumber = 3;
do {
System.out.println(doWhileNumber);
doWhileNumber--;
} while(doWhileNumber > 0);
for-loop
System.out.println("--- forNumber:");
for(int iterator = 0; iterator <= 5; iterator++) {
System.out.println(iterator);
}
Beispiel Ausführung
int myNumber = 1;
// count, how many times we can add 2 until we reach 16,
// but we pretend, 13 doesn't exist for reasons
for(int counter = 0; counter <= 10; counter++) {
myNumber += 2;
if (myNumber == 13) {
continue;
}
System.out.println(counter);
if (myNumber >= 16) {
break;
}
}
Hinweis
Vermeidet einfache Variablennamen wie i, u, usw.m um die Lesbarkeit einfach zu halten
//
for(int i = 0; i < 10; i++) {
for(int u = 30; i > 15; u++) {
myArray[u][i] = i + u;
}
}
for-each-loop
arrays
int[] myArray = {1, 2, 3};
for(int selectedValue: myArray) {
System.out.println("myArray: " + selectedValue);
selectedValue = 0;
}
System.out.println(Arrays.toString(myArray));
for(int selection: myArray) {
System.out.println(selection);
}
lists
LinkedList<String> myLinkedList = new LinkedList<>();
myLinkedList.add("List_1");
myLinkedList.add("List_2");
myLinkedList.add("List_3");
for(int selectedValue: myArray) {
System.out.println(selectedValue);
}
maps
HashMap<Integer, String> myHashMap = new HashMap<>();
myHashMap.put(1, "Larry");
myHashMap.put(2, "Steve");
myHashMap.put(3, "James");
myHashMap.forEach((key, value) -> {
System.out.println(key + " " + value);
});
Exceptions
public class Main {
public static void main(String[] args) {
// simple exception handling
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception exception) {
System.out.println(exception);
System.out.println("---");
}
// extended exception handling
try {
int[] myNumbers = {1, 2, 3};
printTenthIndex(myNumbers);
} catch (RuntimeException exception) {
System.out.println("class: " + exception.getClass()); // class: class java.lang.RuntimeException
System.out.println("cause: " + exception.getCause()); // cause: java.lang.RuntimeException: array is not big enough
System.out.println("message: " + exception.getMessage()); // message: index was not found
} finally {
System.out.println("finally! The 'try catch' is finished.");
}
}
public static void printTenthIndex(int[] array) throws RuntimeException {
Exception r = new RuntimeException("array is not big enough"); // not every exception supports causes
if (array.length < 11) {
throw new RuntimeException("index was not found", r);
}
System.out.println(array[10]);
}
}
03: Coding Style
Programme können sehr schnell sehr komplex werden. Daher ist es wichtig, sich an Stil-Regeln zu halten, um sie möglichst verständlich zu schreiben.
1. Selbsterklärend
Code sollte sich so gut wie möglich selbst erklären.
Dazu sind sprechende Variablen-, Funktions-, Klassennamen etc. erforderlich.
Kurze Namen sind nur in kleinen Gültigkeitsbereichen oder bei klarer Bedeutung
(z.B. i
für for-Schleifen Iteratoren, y
für vertikale Position) erlaubt.
1.1 Kommentare
Kommentare sind in diesem Zusammenhang vorallem zur Strukturierung/Abgrenzung des Codes empfohlen, und um die Verständlichkeit zu erhöhen. Kommentare sollten nicht das Offensichtliche wiederholen (siehe Bild).
Selbstverständlich kann Code zum besseren eigenen Verständnis kommentiert werden. Denken Sie aber daran, dass bei Code Änderungen auch die Kommentare mit gepflegt werden müssen.
4. Benennung
Die folgenden Regelungen sind empfohlen und in keinster Weise verpflichtend.
4.1 camelCase für Variablen und Funktionen
Variablen- und Funktionsnamen beginnen mit Kleinbuchstaben und folgen der
camelCase Notation, d.h. bei zusammengesetzten
Namen beginnen die Wortteile im Inneren mit einem Großbuchstaben.
Funktionsnamen beschreiben dabei eine Aktivität (
z.B. calculateHorizontalPosition()
) oder eine Frage (z.B. isHit()
).
Gleiches gilt für Attribute und Methoden.
4.2 Unterstrich vor formalen Parametern
Formale Parameter folgen dem Variablen-Benennungs-Schema, mit dem Zusatz eines
Unterstriches am Anfang.
(z.B. moveTo(_x: number, _y: number)
).
4.3 PascalCase für Klassen und Interfaces
Die Namen von Klassen und Interfaces beginnen mit einem Großbuchstaben und
folgen sonst der Kamelnotation (also
PascalCase).
Klassen und Interfaces beschreiben im Normalfall ein bestimmtes Objekt, nicht
eine Gruppe von Objekten.
Dies sollte sich im Namen wiederspiegeln (Produkt
statt Produkte
).
4.4 Großschreibung für Enumeratoren
Die Namen von Enumerationen und deren Elemente werden durchgehend mit Großbuchstaben geschreiben. Wortteile werden bei Bedarf mit Unterstrich getrennt.
5. Doppelte und einfache Anführungszeichen
Es empfielt sich, einfache Anführungszeichen ' '
für char und doppelte
Anführungszeichen " "
für Strings zu verwenden.
6. Formatierung
Code ist sinnvoll Formatiert mit Einschüben etc. Im Regelfall unterstützt VSCode dies Automatisch. Machen Sie Gebrauch von der automatischen Formatierungsfunktion.
8. "Magische" Zahlen
Der Gebrauch von "magischen" Zahlen sollte vermieden werden. Solange es nicht
extrem offensichtlich ist, wofür eine Zahl
steht (z.B. Math.pow(x, 5)
), sollte eine Variable (nach den oben genannten
Guidelines) angelegt werden, welcher die
Zahl als Wert zugewiesen wird. So entsteht der Zusammenhang zwischen der
Variablen und ihrer Bedeutung, und der Wert
kann an einer zentralen Stelle angepasst werden.
9. Dateinamen und -aufteilung
Dateinamen dürfen keine Leerzeichen oder Umlaute enthalten, sind sonst aber frei
wählbar (s.u. für Einschränkungen). Es
wird empfohlen, die Zeichenwahl auf a-z, A-Z, 0-9 und _ zu beschränken.
Code kann auf mehrere Dateien aufgeteilt werden, sofern dies sinnvoll
erscheint (z.B. um eine Trennung von Funktion und
Daten zu erreichen). Wenn Klassen verwendet werden, sollte jede ihre eigene
Datei bekommen. Sofern eine Datei eine
bestimmte Klasse enthält, soll die Datei mit dem Namen der Klasse benannt sein.
10. Wiederholungen sind schlecht
Code der sich ohne oder nur mit minimalen Änderungen wiederholt, kann in den
allermeisten Fällen besser geschrieben
werden, z.B. über eine Funktion mit Übergabeparametern, oder indem man nur den
geänderten Teil implementiert oder
überschreibt, während der Rest für alles gleich generiert wird.
Dies hat viele Vorteile: Es macht den Code generell übersichtlicher (und damit
besser verständlich), kürzer, und
wartungsfreundlicher.
04: Einführung in Objekte
Kurze Begriffserklärung
Quelle: stackhowto.com
Declaration
Declaring a variable means the first “mention” of the variable, which tells the compiler “Hello, I am here and can be used”. In a statically typed language like Java, this also means that the declared type of the variable is determined. The value itself is not determined during the declaration.
String name; int nbr;
Initialization
The term initialization usually means the first assignment of a value to a variable.
String name = "Thomas"; int nbr = 5;
Instantiation
The term instantiation actually has nothing to do with assigning a value to a variable, even if a new object is sometimes instantiated when a variable is initialized. The term simply means the creation of a new object, i.e. an instance, from a class.
String name = new String("Thomas");
Modifier
Quelle: w3schools.com
Access-Modifier
Modifier | Beschreibung |
---|---|
public | The code is accessible for all classes |
private | The code is only accessible within the declared class |
protected | The code is accessible in the same package and subclasses. |
default | The code is only accessible in the same package. This is used when you don't specify a modifier. |
Non-Access-Modifier
Modifier | Beschreibung |
---|---|
final | The class cannot be inherited by other classes |
abstract | The class cannot be used to create objects (To access an abstract class, it must be inherited from another class. |
#1 Einfache Objekte und Veerbung
Lernziele:
* eine Klasse erzeugen
* eine Klasse aufrufen
* einfache Veerbung
* Polymorphie (Überschreiben von Methoden)
* die Verwendung von this
* die Verwendung von super
// main.java
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal();
myAnimal.makeSound();
Dog myDog = new Dog();
myDog.makeSound();
Cat myCat = new Cat();
myCat.makeSound();
myCat.compareToAnimal();
}
}
// Animal.java
public class Animal {
public boolean isPet;
public Animal() {
System.out.println("## in constructor of Animal");
this.isPet = false; // it doesn't exist for our cats or dogs
}
public void makeSound() {
System.out.println("Yes, animal usually make sounds");
}
}
// Cat.java
public class Cat extends Animal {
public Cat() {
System.out.println("## in constructor of Cat");
this.isPet = true;
}
@Override
public void makeSound() {
System.out.println("meow meow");
}
public void compareToAnimal() {
System.out.println("--- Animal ---");
super.makeSound();
System.out.println("is alive: " + super.isPet);
System.out.println("--- Cat ---");
this.makeSound();
System.out.println("is alive: " + this.isPet);
}
}
// Dog.java
public class Dog extends Animal {
public Dog() {
System.out.println("## in constructor of Dog");
this.isPet = true;
}
@Override
public void makeSound() {
System.out.println("woof woof");
this.isPet = true;
}
public void compareToAnimal() {
System.out.println("--- Animal ---");
super.makeSound();
System.out.println("is alive: " + super.isPet);
System.out.println("--- Cat ---");
this.makeSound();
System.out.println("is alive: " + this.isPet);
}
}
#2 komplexere Vererbung von Klassen
Lernziele: * Erweiterte Veerbung * Modifikatoren für Attribute * Getter und Setter * Konstruktorverkettung
// main.java
public class Main {
public static void main(String[] args) {
Vehicle myVehicle = new Vehicle();
System.out.println("-- myVehicle:");
System.out.println("number of wheels: " + myVehicle.getNumberOfWheels());
System.out.println("max Speed: " + myVehicle.getMaxSpeed());
myVehicle.setMaxSpeed(150);
System.out.println("max Speed: " + myVehicle.getMaxSpeed());
Car myCar = new Car("blue");
System.out.println("-- myCar:");
System.out.println("number of wheels: " + myCar.getNumberOfWheels());
System.out.println("max Speed: " + myCar.getMaxSpeed());
myVehicle.setMaxSpeed(150);
System.out.println("max Speed: " + myCar.getMaxSpeed());
}
}
public class Vehicle {
protected int numberOfWheels;
protected int maxSpeed;
public Vehicle() {
System.out.println("## in default constructor of Vehicle");
this.numberOfWheels = 4;
this.maxSpeed = 100;
}
public Vehicle(int numberOfWheels, int maxSpeed) {
System.out.println("## in constructor of Vehicle");
this.numberOfWheels = numberOfWheels;
this.maxSpeed = maxSpeed;
}
public int getNumberOfWheels() {
return this.numberOfWheels;
}
public int getMaxSpeed() {
return this.maxSpeed;
}
public String printMaxSpeed() {
return this.maxSpeed + " km/h";
}
public void setMaxSpeed(int newMaxSpeed) {
if (newMaxSpeed < 0) {
return;
}
this.maxSpeed = newMaxSpeed;
}
}
public class Car extends Vehicle {
private String color;
public Car(String color) {
super(4, 200); // always needs to be the first statement
System.out.println("## in constructor of Car");
this.color = color;
}
@Override
public void setMaxSpeed(int newMaxSpeed) {
if (newMaxSpeed < 1000) {
System.out.println("No car shall be this slow tbh");
return;
}
this.maxSpeed = newMaxSpeed;
}
}
public class Car extends Vehicle {
private String color;
public Car(String color) {
super(4, 200); // always needs to be the first statement
System.out.println("## in constructor of Car");
this.color = color;
}
@Override
public void setMaxSpeed(int newMaxSpeed) {
if (newMaxSpeed < 1000) {
System.out.println("No car shall be this slow tbh");
return;
}
this.maxSpeed = newMaxSpeed;
}
}
public class Truck extends Vehicle {
private boolean isFireTruck;
private final String hornSound;
public Truck(boolean isFireTruck) {
super(4, 200); // always needs to be the first statement
System.out.println("## in constructor of Truck");
this.isFireTruck = isFireTruck;
this.hornSound = "test";
}
public boolean getIsFireTruck() {
return this.isFireTruck;
}
}
#3 static
in einer Klasse
Lernziele: * statische und dynamische Variablen * statische und dynamische Methoden
// main.java
public class Main {
public static void main(String[] args) {
Counter.printCounterStatic("Static");
Counter.increaseCounterStatic();
Counter.printCounterStatic("Static");
Counter myCounter = new Counter();
Counter.increaseCounterStatic();
myCounter.increaseCounterDynamic();
myCounter.printCounterDynamic("Dynamic");
}
}
public class Counter {
static int counterValueStatic = 0;
int counterValueDynamic = 0;
public static void increaseCounterStatic() {
counterValueStatic++;
}
public void increaseCounterDynamic() {
this.counterValueDynamic++;
}
public void printCounterDynamic(String classID) {
System.out.println(">> execute printCounterDynamic of class " + classID);
System.out.println("static: " + counterValueStatic);
System.out.println("dynamic: " + this.counterValueDynamic);
}
public static void printCounterStatic(String classID) {
System.out.println(">> execute printCounterStatic of class " + classID);
System.out.println("dynamic: " + counterValueStatic);
}
}
05: Typen von Objekten
Enumerations
// SecurityLevel.java
public enum SecurityLevel {
LOW,
MEDIUM,
HIGH;
}
// Main.java
public class Main {
public static void main(String[] args) {
SecurityLevel networkSecurity = SecurityLevel.MEDIUM;
// comparing enum items
System.out.println(networkSecurity == SecurityLevel.HIGH); // false
System.out.println(networkSecurity.compareTo(SecurityLevel.LOW)); // 1
System.out.println(networkSecurity.compareTo(SecurityLevel.MEDIUM)); // 0
System.out.println(networkSecurity.compareTo(SecurityLevel.HIGH)); // -1
// print all possible values
for(SecurityLevel value : SecurityLevel.values()) {
System.out.println(value.ordinal() + " " + value.name() + " " + value);
}
switch (networkSecurity) {
case LOW:
System.out.println("The network security MUST be increased!");
break;
case MEDIUM:
System.out.println("The network security needs improvements");
break;
case HIGH:
System.out.println("The network security is good so far");
break;
}
}
}
Generics
// Main.java
public class Main /*extends Language implements Regex*/ {
public static void main(String[] args) {
SaveState<String> stateFirst = new SaveState<String>("Begin of the story");
SaveState<String> stateSecond = new SaveState<String>("Near last boss fight");
System.out.println(stateFirst);
System.out.println(stateSecond);
System.out.println("second state bigger? " + stateSecond.compareTo(stateFirst));
System.out.println("first state bigger? " + stateFirst.compareTo(stateSecond));
stateFirst.setSaveState("Finished tutorial");
System.out.println(stateFirst.getSaveState());
}
}
// SaveState.java
import java.security.InvalidParameterException;
public class SaveState<T> implements Comparable<SaveState> {
private T saveEntry;
private int saveID = 0;
private static int staticSaveID;
// constructor
SaveState(T saveEntry) throws InvalidParameterException {
if(saveEntry == null) throw new InvalidParameterException("entry shall not be null");
this.saveEntry = saveEntry;
this.saveID = staticSaveID;
staticSaveID++;
}
public int getSaveID() {
return this.saveID;
}
public T getSaveState() {
return this.saveEntry;
}
public void setSaveState(T saveEntry) throws InvalidParameterException {
if(saveEntry == null) throw new InvalidParameterException("entry shall not be null");
this.saveEntry = saveEntry;
}
@Override
public String toString() {
try {
return this.saveID + ": " + this.saveEntry.toString();
} catch (Exception exception) {
System.out.println("T.toString() for Class " + saveEntry.getClass() + " does not exist");
return null;
}
}
@Override
public int compareTo(SaveState object) {
if (this.saveID > object.getSaveID()) {
return 1;
}
if (this.saveID < object.getSaveID()) {
return -1;
}
return 0;
}
}
Abstract and Interface
// Regex.java
public interface Regex {
public String concatStrings(String left, String right);
}
// Main.java
abstract class Language {
public void showLanguage() {
System.out.println("This text is presented to you by Java");
}
public abstract void sayHelloWorld();
}
// Main.java
public class Main extends Language implements Regex {
public static void main(String[] args) {
// Language myLanguage = new Language();
// 'Language' is abstract; cannot be instantiated
Main myObject = new Main();
myObject.sayHelloWorld();
String wortwitz = myObject.concatStrings("du", "schlampe");
System.out.println(wortwitz); // duschlampe
}
@Override
public void sayHelloWorld() {
System.out.println("I refuse to say that!");
}
@Override
public String concatStrings(String left, String right) {
return left + right;
}
}
Collections
import java.util.*;
// Main.java
public class Main {
public static void main(String[] args) {
String[] alphabet = {
"bee",
"apple",
"clown"
};
System.out.println( Arrays.toString(alphabet) );
ArrayList<String> myArrayList = new ArrayList<String>();
TreeSet<String> myTreeSet = new TreeSet<String>();
HashMap<Integer, String> myHashMap = new HashMap<>();
for(String selection: alphabet) {
myArrayList.add(selection);
myTreeSet.add(selection);
myHashMap.put(myHashMap.size(), selection);
}
Set<Integer> mapKeys = myHashMap.keySet();
System.out.println(mapKeys);
Collection<String> mapValues = myHashMap.values();
System.out.println(mapValues);
Iterator<String> arrayListIterator = myArrayList.iterator();
Iterator<String> treeSetIterator = myTreeSet.iterator();
Iterator<String> hashMapIterator = myHashMap.values().iterator();
System.out.println("--- arrayList ---");
for (String selectedValue: myArrayList) {
System.out.println(selectedValue);
}
System.out.println("--- arrayListIterator ---");
while (arrayListIterator.hasNext()) {
System.out.println(arrayListIterator.next());
}
System.out.println("--- treeSet ---");
for (String selectedValue: myTreeSet) {
ystem.out.println(selectedValue);
}
System.out.println("--- treeSetIterator ---");
while (treeSetIterator.hasNext()) {
System.out.println(treeSetIterator.next());
}
System.out.println("--- hashMap ---");
for (Map.Entry<Integer, String> pair : myHashMap.entrySet()) {
System.out.println(pair.getKey() + ": " + pair.getValue());
}
System.out.println("--- hashMapIterator ---");
while (hashMapIterator.hasNext()) {
System.out.println(hashMapIterator.next());
}
}
}
- List - für beliebig große Listen, deren Elemente auch über einen Index zugegriffen werden können,
ArrayList
- Indizierte Liste, deren Größe dynamisch verändert werden kann. Indexzugriffe sind schnell, Größenänderungen sind aufwändig.LinkedList
- Verkettete Liste. Indexzugriffe sind langsam, Einfügen und Löschen ist schnell.
- Set - zur Darstellung von Mengen
HashSet
- ungeordnete Datenmenge (ohne Duplikate)TreeSet
- Sortierte Menge.
- Map - für Paare von Daten verschiedenen Typs.
HashMap
- Menge von (Schlüssel,Wert)-PaarenTreeMap
- nach Schlüsseln sortierte Menge von (Schlüssel,Wert)-Paaren
Collection Interface (List, Set, Map)
Methode | Beschreibung |
---|---|
int size() | liefert die Anzahl der Einträge |
boolean isEmpty() | prüft, ob keine Einträge vorhanden sind |
boolean contains(Object o) | prüft, ob o eingetragen ist |
boolean add(Object o) | prüft, ob alle Elemente aus c enthalten sind |
boolean addAll(Collection c) | trägt alle Elemente aus c ein (optional) |
boolean remove(Object o) | entfernt o (optional) |
boolean removeAll(Collection c) | entfernt die in c angegebenen Elemente (optional) |
boolean retainAll(Collection c) | entfernt alle Elemente, außer die in c angegebenen (optional) |
boolean equals(Object o) | prüft, ob o mit der Collection übereinstimmt |
Iterator iterator() | erzeugt einen Iterator |
void clear() | entfernt alle Elemente (optional) |
List Interface
Methode | Beschreibung |
---|---|
Object get(int i) | liefert das Element an Position i (ohne es zu entfernen) |
int indexOf(Object o) | liefert den Index des ersten Vorkommens von o oder -1 |
Map Interface
Methode | Beschreibung |
---|---|
boolean containsKey(Object key) | prüft, ob ein Datenpaar mit Schlüssel key eingetragen ist |
boolean containsValue(Object value) | prüft, ob ein Datenpaar mit Wert value eingetragen ist |
Object get(Object key) | liefert den eingetragenen Wert zum Schlüssen key |
Object put(Object key, Object value) | trägt das Datenpaar(key,value) ein (optional) |
boolean remove(Object key) | entfernt das Datenpaar mit Schlüssel key (optional) |
Iteratoren (List, Set)
Methode | Beschreibung |
---|---|
boolean hasNext() | prüft, ob ein weiteres Element existiert |
Object next() | liefert das nächste Element und schaltet weiter |
void remove() | löscht das aktuelle Element |
ListIterator (List)
Methode | Beschreibung |
---|---|
boolean hasPrevious() | prüft, ob ein Vorgänger existiert |
Object previous() | liefert das vorherige Element |
void add(Object o) | fügt ein neues Element o hinter dem aktuellen Element ein |
void set(Object o) | ersetzt das aktuelle Element durch o |
06: JavaDoc
Quelle: JavaDoc Cheatsheet
Output as PDF: JavaDoc from class Main
/**
* This is the Main class
* @version 1.0.1
* @author Justin Drtvic
*/
// Main.java
public class Main {
/**
* this is the main function, which is needed to execute the code
* @param args params passed by the command line
*/
public static void main(String[] args) {
System.out.println( addition(1,2) );
}
/**
* addition of two integer numbers
* @param left number for left side
* @param right number for right side
* @return sum of two numbers
* @throws IllegalArgumentException for numbers smaller than 0
* @see Math
* @see <a href="https://www.mathebibel.de/addition/">Mathebibel Addition</a>
* @since Java API 7
* @deprecated deprecated since 3.0.0
*/
public static int addition(int left, int right) {
if (left < 0 || right < 0) {
throw new IllegalArgumentException("we don't like numbers smaller than 0");
}
return left + right;
}
}