1
0
Fork 0

Updated examples

master
Thomas Smits 2023-02-18 15:27:55 +01:00
commit 75e72c3adf
600 changed files with 14869 additions and 0 deletions

View File

@ -0,0 +1,14 @@
package pr2.ads.adt;
public class BinaryTree {
private TreeNode head;
private TreeNode nullNode;
public BinaryTree() {
head = new TreeNode(null);
nullNode = new TreeNode(null);
head.setRight(nullNode);
nullNode.setLeft(nullNode);
nullNode.setRight(nullNode);
}
}

View File

@ -0,0 +1,8 @@
package pr2.ads.adt;
public interface Queue {
public void enter(Object obj) throws QueueException;
public Object leave() throws QueueException;
public Object front() throws QueueException;
public boolean isEmpty();
}

View File

@ -0,0 +1,4 @@
package pr2.ads.adt;
public class QueueException extends RuntimeException {
}

View File

@ -0,0 +1,8 @@
package pr2.ads.adt;
public interface Stack {
void push(Object obj) throws StackException;
Object pop() throws StackException;
Object top() throws StackException;
boolean isEmpty();
}

View File

@ -0,0 +1,4 @@
package pr2.ads.adt;
public class StackException extends RuntimeException {
}

View File

@ -0,0 +1,22 @@
package pr2.ads.adt;
public class TreeNode {
TreeNode left = null;
TreeNode right = null;
Object key;
public TreeNode(Object o) { key = o; }
public Object getKey() { return key; }
public TreeNode getLeft() { return left; }
public TreeNode getRight() { return right; }
public void setLeft(TreeNode n) { left = n; }
public void setRight(TreeNode n) { right = n; }
public String toString() { return key.toString (); }
}

View File

@ -0,0 +1,23 @@
package pr2.ads.searching;
public class BinarySearch implements Searcher {
@Override
public int search(int e, int[] data) {
int u = 0;
int o = data.length - 1;
while (u <= o) {
int m = (u + o) / 2;
if (data[m] == e) {
return m;
}
else if (data[m] > e) {
o = m - 1;
}
else {
u = m + 1;
}
}
return NOT_FOUND;
}
}

View File

@ -0,0 +1,14 @@
package pr2.ads.searching;
public class LinearSearch implements Searcher {
@Override
public int search(int e, int[] data) {
for (int i = 0; i < data.length; i++) {
if (e == data[i]) {
return i;
}
}
return NOT_FOUND;
}
}

View File

@ -0,0 +1,8 @@
package pr2.ads.searching;
public interface Searcher {
int NOT_FOUND = -1;
int search(int e, int[] data);
}

View File

@ -0,0 +1,27 @@
package pr2.ads.searching;
import java.util.Random;
public class TestSearch {
public static void main(String[] args) {
final int size = 1000;
var data = new int[size];
var r = new Random();
for (int i = 0; i < data.length; i++) {
data[i] = i;
}
Searcher s;
int index;
s = new LinearSearch();
index = s.search(r.nextInt(size), data);
System.out.println(index);
s = new BinarySearch();
index = s.search(r.nextInt(size), data);
System.out.println(index);
}
}

View File

@ -0,0 +1,18 @@
package pr2.ads.shuffle;
import java.util.Random;
public class FisherYatesShuffle implements Shuffler {
@Override
public void shuffle(int[] data) {
Random rand = new Random();
for (int i = data.length - 1; i > 0; i--) {
int randomIndexToSwap = rand.nextInt(data.length);
int temp = data[randomIndexToSwap];
data[randomIndexToSwap] = data[i];
data[i] = temp;
}
}
}

View File

@ -0,0 +1,28 @@
package pr2.ads.shuffle;
import java.util.LinkedList;
import java.util.Random;
public class NaiveShuffle implements Shuffler {
@Override
public void shuffle(int[] data) {
Random rand = new Random();
int n = data.length;
var result = new int[n];
var index = new LinkedList<Integer>();
for (int i = 0; i < n; i++) {
index.add(i);
}
for (int i = 0; i < n; i++) {
int z = rand.nextInt(n - i);
result[i] = data[index.get(z)];
index.remove(z);
}
System.arraycopy(result, 0, data, 0, n);
}
}

View File

@ -0,0 +1,12 @@
package pr2.ads.shuffle;
public interface Shuffler {
void shuffle(int[] data);
default void fill(int[] data) {
for (int i = 0; i < data.length; i++) {
data[i] = i;
}
}
}

View File

@ -0,0 +1,20 @@
package pr2.ads.shuffle;
import java.util.Arrays;
public class TestShuffle {
public static void main(String[] args) {
Shuffler naive = new NaiveShuffle();
Shuffler fisher = new FisherYatesShuffle();
int[] data = new int[10];
naive.fill(data);
naive.shuffle(data);
System.out.println(Arrays.toString(data));
fisher.fill(data);
fisher.shuffle(data);
System.out.println(Arrays.toString(data));
}
}

View File

@ -0,0 +1,24 @@
package pr2.ads.sorting;
public class BubbleSort implements Sorter {
@Override
public void sort(int[] data) {
boolean swapped;
do {
swapped = false;
for (int i = 0; i < data.length - 1; i++) {
if (data[i] > data[i + 1]) {
// Elemente vertauschen
swap(data, i, i + 1);
swapped = true;
}
}
} while (swapped);
}
@Override
public String toString() {
return "BubbleSort";
}
}

View File

@ -0,0 +1,28 @@
package pr2.ads.sorting;
public class InsertionSort implements Sorter {
@Override
public void sort(int[] data) {
for (int i = 1; i < data.length; i++) {
int m = data[i];
int j = i;
while (j > 0) {
if (data[j - 1] >= m) {
/* Verschiebe data[j - 1] eine Position nach rechts */
data[j] = data[j - 1];
j--;
}
else {
break;
}
}
data[j] = m;
}
}
@Override
public String toString() {
return "InsertionSort";
}
}

View File

@ -0,0 +1,46 @@
package pr2.ads.sorting;
public class MergeSort implements Sorter {
void msort(int[] array, int le, int ri, int[] helper) {
int i, j, k;
if (ri > le) {
// zu sortierendes Feld teilen
int mid = (ri + le) / 2;
// Teilfelder sortieren
msort(array, le, mid, helper);
msort(array, mid + 1, ri, helper);
// Hilfsfeld aufbauen
for (k = le; k <= mid; k++) {
helper[k] = array[k];
}
for (k = mid; k < ri; k++) {
helper[ri + mid - k] = array[k + 1];
}
// Ergebnisse mischen über Hilfsfeld
i = le; j = ri;
for (k = le; k <= ri; k++) {
if (helper[i] < helper[j]) {
array[k] = helper[i++];
} else {
array[k] = helper[j--];
}
}
}
}
@Override
public void sort(int[] data) {
int[] helper = new int[data.length];
msort(data, 0, data.length - 1, helper);
}
@Override
public String toString() {
return "MergeSort";
}
}

View File

@ -0,0 +1,47 @@
package pr2.ads.sorting;
public class QuickSort implements Sorter {
int partition(int[] array, int u, int o, int p) {
int pn = u;
int pv = array[p];
// Pivot-Element an das Ende verschieben
swap(array, p, o);
for (int i = u; i < o; i++) {
if (array[i] <= pv) {
swap(array, pn++, i);
}
}
// Pivot-Element an die richtige Position kopieren
swap(array, o, pn);
// neue Pivot-Position zurückgeben
return pn;
}
// Hilfsmethode zum rekursiven Sortieren
void qsort(int[] array, int u, int o) {
// Pivot-Element bestimmen
int p = (u + o) / 2;
if (o > u) {
// Feld zerlegen
int pn = partition(array, u, o, p);
// und Partitionen sortieren
qsort(array, u, pn - 1);
qsort(array, pn + 1, o);
}
}
@Override
public void sort(int[] data) {
qsort(data, 0, data.length - 1);
}
@Override
public String toString() {
return "QuickSort";
}
}

View File

@ -0,0 +1,26 @@
package pr2.ads.sorting;
public class SelectionSort implements Sorter {
@Override
public void sort(int[] data) {
int marker = data.length - 1;
while (marker >= 0) {
// bestimme größtes Element
int max = 0;
for (int i = 1; i <= marker; i++) {
if (data[i] > data[max]) {
max = i;
}
}
// tausche array[marker] mit diesem Element
swap(data, marker, max);
marker--;
}
}
@Override
public String toString() {
return "SelectionSort";
}
}

View File

@ -0,0 +1,12 @@
package pr2.ads.sorting;
public interface Sorter {
void sort(int[] data);
default void swap(int[] data, int i1, int i2) {
int tmp = data[i1];
data[i1] = data[i2];
data[i2] = tmp;
}
}

View File

@ -0,0 +1,75 @@
package pr2.ads.sorting;
import pr2.nestedclasses.lambda.function.RechnerKurz;
import java.util.*;
public class TestSorting {
private static void shuffle(int[] data) {
Random rand = new Random();
for (int i = 0; i < data.length; i++) {
int randomIndexToSwap = rand.nextInt(data.length);
int temp = data[randomIndexToSwap];
data[randomIndexToSwap] = data[i];
data[i] = temp;
}
}
static long testAlgorithm(Class clazz, int size, int runs) {
Sorter s;
var data = new int[size];
for (int i = 0; i < data.length; i++) {
data[i] = i;
}
long start = System.nanoTime();
try {
s = (Sorter) clazz.getDeclaredConstructor().newInstance();
for (int i = 0; i < runs; i++) {
shuffle(data);
s.sort(data);
}
}
catch (Exception e) {
// do nothing
return 0;
}
long runtime = System.nanoTime() - start;
return runtime;
}
public static void measure(int size_steps, int max_size, int runs) {
System.out.println("Runs\tBS\tIS\tMS\tQS\tSS");
for (int size = 0; size <= max_size; size += size_steps) {
long bs = testAlgorithm(BubbleSort.class, size, runs);
long is = testAlgorithm(InsertionSort.class, size, runs);
long ms = testAlgorithm(MergeSort.class, size, runs);
long qs = testAlgorithm(QuickSort.class, size, runs);
long ss = testAlgorithm(SelectionSort.class, size, runs);
System.out.printf("%d\t%d\t%d\t%d\t%d\t%d\n", size, bs, is, ms, qs, ss);
}
}
public static void main(String[] args) {
measure(10, 1000, 100);
final int size = 1000;
final int runs = 1000;
testAlgorithm(BubbleSort.class, size, runs);
testAlgorithm(InsertionSort.class, size, runs);
testAlgorithm(MergeSort.class, size, runs);
testAlgorithm(QuickSort.class, size, runs);
testAlgorithm(SelectionSort.class, size, runs);
}
}

View File

@ -0,0 +1,49 @@
package pr2.ads.textsearch;
import java.util.HashMap;
import java.util.Map;
public class BoyerMooreTextSearch implements TextSearch {
public int search(String haystack, String needle) {
char[] text = haystack.toCharArray();
char[] pattern = needle.toCharArray();
int n = text.length;
int m = pattern.length;
// Test for empty string
if (m == 0) return 0;
// Initialization, create Map of last position of each character = O(n)
Map<Character, Integer> last = new HashMap<>();
for (char c : text) {
// set all chars, by default, to -1
last.put(c, -1);
}
for (int i = 0; i < m; i++) {
// update last seen positions
last.put(pattern[i], i);
}
//Start with the end of the pattern aligned at index m-1 in the text.
//index into the text
int i = m - 1;
// index into the pattern
int k = m - 1;
while (i < n) {
if (text[i] == pattern[k]) {
// match! return i if complete match; otherwise, keep checking
if (k == 0) {
return i;
}
i--; k--;
}
else { // jump step + restart at end of pattern
//iterate over text
i += m - Math.min(k, 1 + last.get(text[i]));
//move to end of pattern
k = m - 1;
}
}
// not found
return NOT_FOUND;
}
}

View File

@ -0,0 +1,22 @@
package pr2.ads.textsearch;
public class BruteForceTextSearch implements TextSearch {
public int search(String haystack, String needle) {
int n = haystack.length();
int m = needle.length();
for (int i = 0; i <= n - m; i++) {
int j;
for (j = 0; j < m; j++) {
if (haystack.charAt(i + j) != needle.charAt(j)) {
break;
}
}
if (j == m) {
return i;
}
}
return NOT_FOUND;
}
}

View File

@ -0,0 +1,46 @@
package pr2.ads.textsearch;
public class KMPTextSearch implements TextSearch {
public int search(String haystack, String needle) {
int[] lps = computeLPS(needle);
int i = 0, j = 0;
while (i < haystack.length()) {
if (needle.charAt(j) == haystack.charAt(i)) {
i++;
j++;
}
if (j == needle.length()) {
return i - j;
} else if (i < haystack.length() && needle.charAt(j) != haystack.charAt(i)) {
if (j != 0) {
j = lps[j - 1];
} else {
i = i + 1;
}
}
}
return -1;
}
public int[] computeLPS(String pattern) {
int[] lps = new int[pattern.length()];
int j = 0;
for (int i = 1; i < pattern.length();) {
if (pattern.charAt(i) == pattern.charAt(j)) {
lps[i] = j + 1;
i++;
j++;
} else {
if (j != 0) {
j = lps[j - 1];
} else {
lps[i] = 0;
i++;
}
}
}
return lps;
}
}

View File

@ -0,0 +1,21 @@
package pr2.ads.textsearch;
public class TestTextSearch {
public static void main(String[] args) {
String haystack = "DASISTEINSINNLOSERTEXT";
String needle = "SINN";
TextSearch bf = new BruteForceTextSearch();
System.out.println(bf.search(haystack, needle));
TextSearch kmp = new KMPTextSearch();
System.out.println(kmp.search(haystack, needle));
TextSearch bm = new BoyerMooreTextSearch();
System.out.println(bm.search(haystack, needle));
}
}

View File

@ -0,0 +1,8 @@
package pr2.ads.textsearch;
public interface TextSearch {
int NOT_FOUND = -1;
int search(String haystack, String needle);
}

View File

@ -0,0 +1,39 @@
/*
* (c) 2010 Thomas Smits
*/
package pr2.auffrischung;
/**
* Klasse dient als Beispiel für den Coding-Standard und die Namenskonventionen
* bei Java-Programmen.
*
* @author Thomas Smits
*/
public class CodingStandard {
/**
* Konstante, die dem Rest der Welt etwas mitteilen soll.
*/
public static final int KONSTANTE_MIT_TOLLEM_WERT = 3;
private int erstesFeld;
private double zweitesFeld;
/**
* Methode, die etwas tut - oder auch nicht ;-).
*
* @param parameter Eingabewert für die Methode
* @return gibt immer 42 zurück
*/
public int methodeDieWasTut(int parameter) {
if (parameter > 3) {
erstesFeld = 12;
}
else {
zweitesFeld = 13;
}
return 42;
}
}

View File

@ -0,0 +1,29 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.auffrischung;
public class Ding {
// Dies ist ein Kommentar in einer Zeile
/* dies ist ein Kommentar
über mehrere Zeilen */
/** Hier kommt JavaDoc */
/** Hier kommt JavaDoc,
* gerne auch Mehrzeilig */
private int x;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
// Testkommentar
}

View File

@ -0,0 +1,22 @@
/* (c) 2022 Thomas Smits */
package pr2.auffrischung;
import java.util.Scanner;
/**
*
*
* @author Thomas Smits
*/
public class IsPrim {
@SuppressWarnings("resource")
public static void main(String[] args) {
int r, i = 2, n = new Scanner(System.in).nextInt();
while ((r = (n % i)) != 0 & (i++ < Math.sqrt(n)));
System.out.println(r == 0 ? "Keine Primzahl (" + --i +")" : "Primzahl");
}
//for (int i = 2; (r = (n % i)) != 0 && (i < Math.sqrt(n)); i++);
}

View File

@ -0,0 +1,201 @@
/*
* (c) 2011 Thomas Smits
*/
package pr2.auffrischung;
public class Kontrollstrukturen {
public void doIt() {
int count = getCount(); // Methode im Programm
if (count < 0) {
System.out.println("Fehler: Zahl ist negativ.");
} else if (count > getMaxCount()) {
System.out.println("Fehler: Zahl ist zu groß.");
} else {
System.out.println("Es kommen " + count + " Leute");
}
int mitarbeiterArt = 5;
final int MANAGER = 1;
final int SENIOR_DEVELOPER = 2;
switch (mitarbeiterArt) {
case MANAGER:
addEinzelnesBuero();
addFirmenwagen();
addSekretaerin();
break;
case SENIOR_DEVELOPER:
addEinzelnesBuero();
addFirmenwagen();
break;
default:
addGrossraumbuero();
}
// Kindersimulator
for (int i = 0; i < 10; i++) {
System.out.println("Sind wir schon da?");
System.out.println("Ist es noch weit?");
}
System.out.println("Jetzt sind wir angekommen!");
int i = 0;
for (; i < 10; i++) {
System.out.println("Variable außerhalb deklariert");
}
int j = 0;
for (; j < 10;) {
j++;
System.out.println("Variable außerhalb deklariert");
System.out.println("Inkrement innerhalb");
}
for (i = 0, j = 0; j < 10; i++, j++) { }
int[] primzahlen = { 2, 3, 5, 7, 11, 13, 17, 19};
int summe = 0;
for (int primzahl : primzahlen) {
summe += primzahl;
}
// for (int i = 0; i < primzahlen.length; i++) {
// int primzahl = primzahlen[i];
// summe += primzahl;
// }
for (;;) {
System.out.println("Endlosschleife");
}
}
public void switch12() {
var titel = "Senior";
switch (titel) {
case "Manager" -> {
addEinzelnesBuero();
addFirmenwagen();
addSekretaerin();
}
case "Senior" -> {
addEinzelnesBuero();
addFirmenwagen();
}
default -> addGrossraumbuero();
}
int monat = 2;
int tage;
switch (monat) {
case 2:
tage = 28; break;
case 4:
case 6:
case 9:
case 11:
tage = 30; break;
default:
tage = 31;
}
int days = switch (monat) {
case 2 -> 28;
case 4, 6, 9, 11 -> 30;
default -> 31;
};
}
public void doit2() {
int i = 0;
while (i < 10) {
System.out.println("Sind wir schon da?");
System.out.println("Ist es noch weit?");
i++;
}
System.out.println("Jetzt sind wir angekommen!");
}
public void doit3() {
int i = 0;
do {
System.out.println("Sind wir schon da?");
System.out.println("Ist es noch weit?");
i++;
} while (i < 10);
System.out.println("Jetzt sind wir angekommen!");
do
System.out.println("Hallo");
while (true);
}
private void addGrossraumbuero() {
// TODO Auto-generated method stub
}
private void addSekretaerin() {
// TODO Auto-generated method stub
}
private void addFirmenwagen() {
// TODO Auto-generated method stub
}
private void addEinzelnesBuero() {
// TODO Auto-generated method stub
}
private void addEngine() {
// TODO Auto-generated method stub
}
private void addWheels() {
// TODO Auto-generated method stub
}
private void addRadio() {
// TODO Auto-generated method stub
}
private void addAirConditioning() {
// TODO Auto-generated method stub
}
int getCount() {
return 5;
}
int getMaxCount() {
return 5;
}
}

View File

@ -0,0 +1,18 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.auffrischung;
/**
*
* @author Thomas Smits
*/
public class QuizString {
public static void main(String[] args) {
String s1 = "Hallo";
String s2 = new String("World");
String s3 = s2;
String s4 = s1.toUpperCase().trim();
}
}

View File

@ -0,0 +1,35 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.auffrischung;
class Scope {
int i = 1;
void ersteMethode() {
int i = 4;
int j = 5;
{
int k = 7;
this.i = i + j;
zweiteMethode(k);
}
{
int k = 7;
}
}
void zweiteMethode(int i) {
int j = 8;
this.i = i + j;
}
public static void main(String[] args) {
Scope scope = new Scope();
scope.ersteMethode();
System.out.println(5 * 70 % 6);
System.out.println(5 * (70 % 6));
}
}

View File

@ -0,0 +1,34 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.auffrischung;
public class Zuweisung {
public static void main(String args[]) {
int x, y;
float z = 1.712f;
double w = 3.1415;
boolean wahrheit = true;
char c;
String str;
String str1 = "Hi";
c = 'Z';
str = "Hallo Welt";
x = 60;
y = 400;
int i = 5, j[] = { 1,2,3 }, k[][] = new int[2][3];
}
}

View File

@ -0,0 +1,14 @@
/* (c) 2022 Thomas Smits */
package pr2.auffrischung.quiz;
public class IfWithoutBlock {
public static void main(String[] args) {
boolean b = false;
if (b)
System.out.println("b ist true");
System.out.println("b ist true");
}
}

View File

@ -0,0 +1,113 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.auffrischung.quiz;
public class Puzzles {
public static void main(String[] args) {
{
// Integer Division
int i = 1;
double d;
d = i / 2;
System.out.println(d);
d = (double) i / 2;
System.out.println(d);
d = i / 2.0;
System.out.println(d);
}
{
// If und Zuweisung
boolean b = false;
if (b = true) {
System.out.println("Oops");
}
}
{
// Case fallthru
int x = 3;
switch (x) {
case 1:
System.out.println("1");
case 2:
System.out.println("2");
case 3:
System.out.println("3");
case 4:
System.out.println("4");
default:
System.out.println("Passt nicht");
}
}
{
// Wetebreich
byte b = 127;
b++;
System.out.println(b);
}
{
// // Array-Indizes
// int[] array = new int[5];
//
// for (int i = 1; i < 6; i++) {
// array[i] = i;
// }
}
{
// // Und / Oder ohne Kurzschluss
// String s = null;
//
// if ((s != null) & (s.length() > 0)) {
// System.out.println(s.charAt(0));
// }
}
}
void swap(String a, String b) {
String temp = a;
a = b;
b = temp;
}
void testSwap() {
String a = "Hallo";
String b = "Welt";
swap(a, b);
System.out.println(a + " " + b);
}
/* Swap funktioniert nicht :-(
void methodeMitKommentaren() {
// Erzeuge zwei Strings mit sinnvollem Inhalt
String a = "Hallo";
String b = "Welt";
// Vertausche die Variablen
swap(a, b);
// Drucke Ergebnis aus
System.out.println(a + " " + b);
}
*/
}

View File

@ -0,0 +1,17 @@
/* (c) 2022 Thomas Smits */
package pr2.auffrischung.quiz;
import java.awt.Point;
public class Reference {
public static void main(String[] args) {
Point p1 = new Point(3, 4);
Point p2 = p1;
p2.setLocation(5, 6);
System.out.println(p1);
System.out.println(p2);
}
}

View File

@ -0,0 +1,22 @@
/* (c) 2022 Thomas Smits */
package pr2.auffrischung.quiz;
public class Swap {
void swap(String s1, String s2) {
String temp = s1;
s1 = s2;
s2 = temp;
}
void swapMe() {
String s1 = "Hallo";
String s2 = "Welt";
swap(s1, s2);
System.out.println(s1 + " " + s2);
}
public static void main(String[] args) {
new Swap().swapMe();
}
}

View File

@ -0,0 +1,118 @@
/* (c) 2022 Thomas Smits */
package pr2.ausnahmen;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
*
*
* @author Thomas Smits
*/
public class Java7 {
/**
* @param args the command line arguments.
*/
public static void main(String[] args) {
String titel = "Noob";
switch (titel) {
case "Manager":
break;
case "Senior":
break;
default:
break;
}
List<String> list = new ArrayList<>();
Map<Integer, String> map = new HashMap<>();
Set<?> set = new HashSet<>();
new Java7().catchThrow();
try {
openFile();
writeToDatabase();
}
catch (FileNotFoundException | SQLException e) {
System.out.println("Ohje, alles kapput...:" + e);
}
}
public static void openFile() throws FileNotFoundException {
throw new FileNotFoundException();
}
public static void writeToDatabase() throws SQLException {
throw new SQLException();
}
public void catchThrow() {
try {
try {
openFile();
}
catch (IOException e) {
throw e;
}
}
catch (Exception e) {
System.out.println(e.getClass());
}
}
public void resources() {
try(FileInputStream fis = new FileInputStream("/tmp/file1");
FileOutputStream fos = new FileOutputStream("/tmp/file2")) {
int i = fis.read();
fos.write(i);
}
catch (IOException e) {
// Ausnahme behandeln
}
}
public void resourcesOld() throws IOException {
FileInputStream fis = new FileInputStream("/tmp/file1");
FileOutputStream fos = new FileOutputStream("/tmp/file2");
try {
int i = fis.read();
fos.write(i);
}
catch (IOException e) {
// Ausnahme behandeln
}
finally {
try {
fis.close();
}
catch (IOException e) { /* ignore */ }
try {
fos.close();
}
catch (IOException e) { /* ignore */ }
}
}
}

View File

@ -0,0 +1,40 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.ausnahmen.callstack;
import java.io.FileInputStream;
import java.io.IOException;
public class CallStack1 {
public static void main(String[] args) {
if (args.length < 1) {
System.err.println("Bitte Dateinamen angeben.");
System.exit(4);
}
try {
mergeData(args[0], "/tmp/output");
} catch (IOException e) {
System.err.printf("Datei %s gibt es nicht%n%n", args[0]);
}
}
public static void mergeData(String inFile, String outFile)
throws IOException {
writeData(inFile, outFile);
}
public static void writeData(String inFile, String outFile) throws IOException {
aggregate(5, 5, inFile);
}
public static int aggregate(int a, int b, String inFile) throws IOException {
FileInputStream f = new FileInputStream(inFile);
f.close();
return 1;
}
}

View File

@ -0,0 +1,29 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.ausnahmen.callstack;
import java.io.FileInputStream;
import java.io.IOException;
public class CallStack2 {
public static void main(String[] args) throws IOException {
mergeData("/tmp/input", "/tmp/output");
}
public static void mergeData(String inFile, String outFile)
throws IOException {
writeData(outFile);
}
public static void writeData(String outFile) throws IOException {
aggregate(5, 5);
}
public static int aggregate(int a, int b) throws IOException {
FileInputStream f = new FileInputStream("/tmp/input");
f.close();
return 1;
}
}

View File

@ -0,0 +1,29 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.ausnahmen.callstack;
import java.io.FileInputStream;
import java.io.IOException;
public class CallStack3 {
public static void main(String[] args) throws IOException {
mergeData(args[0], "/tmp/output");
}
public static void mergeData(String inFile, String outFile)
throws IOException {
writeData(inFile, outFile);
}
public static void writeData(String inFile, String outFile) throws IOException {
aggregate(5, 5, inFile);
}
public static int aggregate(int a, int b, String inFile) throws IOException {
FileInputStream f = new FileInputStream(inFile);
f.close();
return 1;
}
}

View File

@ -0,0 +1,53 @@
package pr2.ausnahmen.callstack;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
/**
* @author Thomas Smits
*/
public class HandleOrDeclare {
public void openFile(String dateiName)
throws IOException, FileNotFoundException {
// Datei öffnen
}
public void datenSchreiben(String dateiName, String sqlStatement)
throws FileNotFoundException, IOException, SQLException {
openFile(dateiName);
// Mit Datenbank arbeiten
}
public void dateiAnlegen(String dateiName)
throws FileNotFoundException, IOException {
try {
datenSchreiben(dateiName, "SELECT * FROM x");
}
catch (SQLException ex) {
// Datenbank Problem beheben ;-)
}
}
public void userInterface() {
String dateiName = askUser();
try {
dateiAnlegen(dateiName);
}
catch (FileNotFoundException ex) {
// Benutzer erneut nach namen Fragen
}
catch (IOException ex) {
// Benutzer auf Problem hinweisen
}
}
public String askUser() {
return null;
}
}

View File

@ -0,0 +1,26 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.ausnahmen.eigene;
public class Client {
public void doIt() {
try {
Server.connect("server1", 22);
}
catch (ServerException e1) {
System.err.println("Keine Verbindung zum server "
+ e1.getHost() + " auf Port " + e1.getPort());
try {
Server.connect("server2", 22);
}
catch (ServerException e2) {
System.err.println("Ersatzserver geht auch nicht: "
+ e2.getHost() + " auf Port " + e2.getPort());
}
}
}
}

View File

@ -0,0 +1,21 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.ausnahmen.eigene;
public class Server {
public static void connect(String host, int port) throws ServerException {
int result = connectInternal(host, port);
if (result == -1) {
throw new ServerException("Cannot connect to " + host + ":" + port, host, port);
}
// ...
}
private static native int connectInternal(String host, int port);
}

View File

@ -0,0 +1,24 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.ausnahmen.eigene;
public class ServerException extends Exception {
private int port;
private String host;
public ServerException(String message, String host, int port) {
super(message);
this.host = host;
this.port = port;
}
public int getPort() {
return port;
}
public String getHost() {
return host;
}
}

View File

@ -0,0 +1,27 @@
/* (c) 2022 Thomas Smits */
package pr2.ausnahmen.eigene;
import java.io.IOException;
public class SimpleExample2 {
public static void main(String[] args) {
new SimpleExample2().method();
}
public void method() {
try {
System.out.println("A");
thrower();
System.out.println("B");
}
catch (IOException e) {
System.out.println("Fehler: " + e.getMessage());
}
}
private void thrower() throws IOException {
throw new IOException("Festplatte explodiert");
}
}

View File

@ -0,0 +1,25 @@
/* (c) 2022 Thomas Smits */
package pr2.ausnahmen.eigene;
import java.io.IOException;
public class SimpleExamples {
public static void main(String[] args) {
boolean b = true;
try {
System.out.println("A");
if (b) {
throw new IOException("Festplatte abgebrannt");
}
System.out.println("B");
}
catch (IOException e) {
System.out.println("Fehler: " + e.getMessage());
}
}
}

View File

@ -0,0 +1,46 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.ausnahmen.finall;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TryCatchFinallyExample {
public static void main(String[] args) {
Connection connection = getConnection();
try {
ResultSet rs = readData(connection);
while (rs.next()) {
// Daten bearbeiten
}
return;
}
catch (SQLException ex) {
// Datenbank Problem behandeln
}
finally {
releaseConnection(connection);
}
}
private static ResultSet readData(Connection connection) throws SQLException {
return null;
}
private static Connection getConnection() {
return null;
}
private static void releaseConnection(Connection connection) {
}
}

View File

@ -0,0 +1,51 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.ausnahmen.finall;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TryCatchFinallyExample2 {
public static void main(String[] args) {
Connection connection = getConnection();
try {
ResultSet rs = readData(connection);
while (rs.next()) {
// Daten bearbeiten
}
return;
}
catch (SQLException ex) {
// Datenbank Problem behandeln
}
finally {
try {
releaseConnection(connection);
}
catch (SQLException ex) {
// Hier kann man nichts mehr machen
}
}
}
private static ResultSet readData(Connection connection) throws SQLException {
return null;
}
private static Connection getConnection() {
return null;
}
private static void releaseConnection(Connection connection) throws SQLException {
}
}

View File

@ -0,0 +1,25 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.ausnahmen.junit;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Assertions;
public class BrokenTest {
@Test
public void testKaputt() {
String s1 = new String("Hallo");
assertEquals("Hallo", s1);
Assertions.assertThrows(NullPointerException.class, () -> {
new String((String) null);
new String((char[]) null);
});
String s3 = new String("World");
assertEquals("world", s3);
}
}

View File

@ -0,0 +1,18 @@
package pr2.ausnahmen.junit;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions;
/*
* (c) 2009 Thomas Smits
*/
public class TestMitExpected {
@Test
public void testAufAusnahme() {
Assertions.assertThrows(NullPointerException.class, () -> {
new String((String) null);
});
}
}

View File

@ -0,0 +1,25 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.ausnahmen.junit;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;
public class TestMitTryCatch {
@Test
public void testAufAusnahme() {
try {
new String((String) null);
fail();
}
catch (NullPointerException ex) {
assertTrue(true);
}
}
}

View File

@ -0,0 +1,21 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.ausnahmen.quiz;
public class Finally {
@SuppressWarnings("finally")
public static boolean f() {
try {
return true;
}
finally {
return false;
}
}
public static void main(String[] args) {
System.out.println(f());
}
}

View File

@ -0,0 +1,42 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.ausnahmen.trycatch;
import java.io.FileInputStream;
import java.io.IOException;
/**
*
*
* @author Thomas Smits
*/
public class BlossNicht {
@SuppressWarnings("null")
public static void main(String[] args) throws IOException {
try {
FileInputStream fis = new FileInputStream("/tmp/gibtsnicht");
String s = null;
s = s.toUpperCase();
fis.close();
}
catch (Exception e) {
// Fehlerbehandlung
}
FileInputStream fis = null;
try {
fis = new FileInputStream("/tmp/gibtsnicht");
}
catch (Exception e) {
e.printStackTrace();
}
fis.read();
}
}

View File

@ -0,0 +1,16 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.ausnahmen.trycatch;
public class ExceptionExample {
public static void main(String[] args) {
String[] namen = { "Franz", "Hans", "Alfons" };
for (int i = 0; i < 4; i++) {
System.out.print(namen[i] + ", ");
}
}
}

View File

@ -0,0 +1,23 @@
/* (c) 2022 Thomas Smits */
package pr2.ausnahmen.trycatch;
public class FinallyMitSeiteneffekt {
private static int changeMe = 41;
public static void main(String[] args) {
System.out.println(m());
System.out.println(changeMe);
}
@SuppressWarnings("finally")
static int m() {
try {
return changeMe++;
}
finally {
return changeMe++;
}
}
}

View File

@ -0,0 +1,22 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.ausnahmen.trycatch;
public class GanzBoese {
public static void printArray(int[] array) {
try {
for (int i = 0;;i++) {
System.out.println(array[i]);
}
}
catch (ArrayIndexOutOfBoundsException ex) {
}
}
public static void main(String[] args) {
printArray(new int[] { 1,2,3,4,5,6,7,8,9,10 });
}
}

View File

@ -0,0 +1,36 @@
/* (c) 2022 Thomas Smits */
package pr2.ausnahmen.trycatch;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
/**
* Beispiel für Netzwerk-Verbindung mit Java-Fehlerbehandlung.
*
* @author Thomas Smits
*/
public class Netzwerk {
@SuppressWarnings("resource")
public static void main(String[] args) {
try {
ServerSocket servSocket = new ServerSocket();
servSocket.bind(new InetSocketAddress(8080));
for (;;) {
Socket clntSocket = servSocket.accept();
// ...
}
}
catch (SocketTimeoutException e) {
// Fehlerbehandlung
}
catch (IOException e) {
// Fehlerbehandlung
}
}
}

View File

@ -0,0 +1,40 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.ausnahmen.trycatch;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TryCatchExample {
public static void main(String[] args) {
Connection connection = getConnection();
try {
ResultSet rs = readData(connection);
while (rs.next()) {
// Daten bearbeiten
}
}
catch (SQLException ex) {
// Datenbank Problem behandeln
String sqlStatus = ex.getSQLState();
// ...
ex.printStackTrace();
}
}
private static ResultSet readData(Connection connection) throws SQLException {
return null;
}
private static Connection getConnection() {
return null;
}
}

View File

@ -0,0 +1,52 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.ausnahmen.trycatch;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TryCatchExampleZwei {
public static void main(String[] args) {
Connection connection = getConnection();
try {
ResultSet rs = readData(connection);
while (rs.next()) {
storeToFile(rs.getString(0), rs);
}
}
catch (SQLException ex) {
// Datenbank-Problem
ex.printStackTrace();
}
catch (FileNotFoundException ex) {
// Datei nicht gefunden
System.out.println(ex.getMessage());
}
catch (IOException ex) {
// Allgemeiner IO-Fehler
System.out.println(ex.getMessage());
}
}
private static ResultSet readData(Connection connection) throws SQLException {
return null;
}
private static Connection getConnection() {
return null;
}
public static void storeToFile(String fileName, ResultSet rs) throws FileNotFoundException, IOException {}
}

View File

@ -0,0 +1,12 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.ausnahmen.trycatch.polymorphie;
import java.io.IOException;
public class A {
public void method() throws IOException {
}
}

View File

@ -0,0 +1,31 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.ausnahmen.trycatch.polymorphie;
import java.io.FileNotFoundException;
import java.io.IOException;
class B extends A {
public void method() throws IOException, FileNotFoundException {
}
}
class C extends A {
public void method() throws FileNotFoundException {
}
}
class D extends A {
public void method() {
}
}
//class E extends A {
//
// public void method() throws SQLException {
// }
//}

View File

@ -0,0 +1,13 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections;
import java.util.Stack;
public class StackDemo {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
}
}

View File

@ -0,0 +1,54 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.interfaces.collection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
public class CollectionDemo {
public static void main(String[] args) {
Collection<String> col1 = new ArrayList<>();
col1.add("Element 1");
col1.add("Element 2");
col1.add("Element 3");
col1.add("Element 4");
System.out.println(col1.size()); // --> 4
System.out.println(col1.contains("Element 3")); // --> true
col1.remove("Element 3");
System.out.println(col1.size()); // --> 3
Collection<String> col2 = new ArrayList<>();
col2.addAll(col1);
System.out.println(col2); // --> [Element 1, Element 2, Element 4]
col1.clear();
System.out.println(col1.size()); // --> 0
col1.add("Element 2");
col2.removeAll(col1);
System.out.println(col2); // --> [Element 1, Element 4]
String[] str1 = new String[col1.size()];
str1 = col1.toArray(str1);
String[] str2 = col2.toArray(new String[0]);
System.out.println(Arrays.asList(str1)); // --> [Element 2]
System.out.println(Arrays.asList(str2)); // --> [Element 1, Element 4]
}
}

View File

@ -0,0 +1,11 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.interfaces.collection;
public class CollectionsDemo {
public static void main(String[] args) {
}
}

View File

@ -0,0 +1,25 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.interfaces.list;
import java.util.ArrayList;
import java.util.List;
public class ListDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Element A");
list.add("Element B");
list.add("Element C");
list.add("Element A");
list.add("Element B");
for (String element : list) {
System.out.println(element);
}
}
}

View File

@ -0,0 +1,41 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.interfaces.list;
import java.util.ArrayList;
import java.util.List;
public class ListDemo2 {
public static void main(String[] args) {
List<String> list1 = new ArrayList<>();
list1.add("Element 1");
list1.add("Element 2");
list1.add("Element 3");
list1.add("Element 4");
System.out.println(list1.get(3)); // --> Element 4
list1.remove(0);
System.out.println(list1); // --> [Element 2, Element 3, Element 4]
list1.add(2, "Eigefuegt");
System.out.println(list1); // --> [Element 2, Element 3, Eigefuegt, Element 4]
List<String> list2 = list1.subList(1, 3);
System.out.println(list2); // --> [Element 3, Eigefuegt]
list2.set(1, "Ausgetauscht");
System.out.println(list2); // --> [Element 3, Ausgetauscht]
list2.add(2, "Eingefuegt");
System.out.println(list2); // --> [Element 3, Ausgetauscht, Eingefuegt]
System.out.println(list2.indexOf("Element 3")); // --> 0
}
}

View File

@ -0,0 +1,25 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.interfaces.set;
import java.util.HashSet;
import java.util.Set;
public class SetDemo {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("Element A");
set.add("Element B");
set.add("Element C");
set.add("Element A");
set.add("Element B");
for (String element : set) {
System.out.println(element);
}
}
}

View File

@ -0,0 +1,21 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.iterable;
import java.util.ArrayList;
public class IterableFor {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Eintrag 1");
list.add("Eintrag 2");
list.add("Eintrag 3");
for (String wert : list) {
System.out.println(wert);
}
}
}

View File

@ -0,0 +1,27 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.iterable;
import java.util.ArrayList;
import java.util.Iterator;
public class IterableWhile {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Eintrag 1");
list.add("Eintrag 2");
list.add("Eintrag 3");
Iterable<String> iterable = list;
Iterator<String> iterator = iterable.iterator();
while (iterator.hasNext()) {
String wert = iterator.next();
System.out.println(wert);
}
}
}

View File

@ -0,0 +1,34 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.iterable;
import java.util.ArrayList;
import java.util.ListIterator;
public class ListIteratorDemo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Eintrag 1");
list.add("Eintrag 2");
list.add("Eintrag 3");
ListIterator<String> iterator = list.listIterator();
iterator.next();
iterator.next();
iterator.previous();
iterator.set("Neuer Eintrag 2");
iterator.next();
iterator.next();
iterator.add("Neuer Eintrag 4");
iterator = list.listIterator();
for (String wert : list) {
System.out.println(wert);
}
}
}

View File

@ -0,0 +1,42 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.iterable.eigenes;
import java.util.Iterator;
public class IterableInnereKlasse implements Iterable<String> {
private String[] stringListe;
public IterableInnereKlasse(String[] stringListe) {
this.stringListe = stringListe;
}
public Iterator<String> iterator() {
return new Iterator<String>() {
private int pos = 0;
public boolean hasNext() {
return (pos < stringListe.length);
}
public String next() {
return stringListe[pos++];
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public static void main(String[] args) {
String[] strings = new String[] { "A", "B", "C", "D" };
IterableInnereKlasse liste = new IterableInnereKlasse(strings);
for (String string : liste) {
System.out.println(string);
}
}
}

View File

@ -0,0 +1,50 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.iterable.eigenes;
import java.util.Iterator;
public class IterableMitKlasse implements Iterable<String> {
private String[] stringListe;
public IterableMitKlasse(String[] stringListe) {
this.stringListe = stringListe;
}
public Iterator<String> iterator() {
return new MyIterator(stringListe);
}
public static void main(String[] args) {
String[] strings = new String[] { "A", "B", "C", "D" };
IterableMitKlasse liste = new IterableMitKlasse(strings);
for (String string : liste) {
System.out.println(string);
}
}
}
class MyIterator implements Iterator<String> {
private int pos = 0;
private String[] stringListe;
public MyIterator(String[] stringListe) {
this.stringListe = stringListe;
}
public boolean hasNext() {
return (pos < stringListe.length);
}
public String next() {
return stringListe[pos++];
}
public void remove() {
throw new UnsupportedOperationException();
}
}

View File

@ -0,0 +1,41 @@
/*
*
*/
package pr2.collections.iterable.eigenes;
import java.util.Iterator;
public class IterableSelbst implements Iterable<String>, Iterator<String> {
private String[] stringListe;
public IterableSelbst(String[] stringListe) {
this.stringListe = stringListe;
}
public Iterator<String> iterator() {
return this;
}
public static void main(String[] args) {
String[] strings = new String[] { "A", "B", "C", "D" };
IterableSelbst liste = new IterableSelbst(strings);
for (String string : liste) {
System.out.println(string);
}
}
private int pos = 0;
public boolean hasNext() {
return (pos < stringListe.length);
}
public String next() {
return stringListe[pos++];
}
public void remove() {
throw new UnsupportedOperationException();
}
}

View File

@ -0,0 +1,45 @@
/*
*
*/
package pr2.collections.iterable.eigenes;
import java.util.Iterator;
public class IterableSelbstKorrekt implements Iterable<String>, Iterator<String> {
private String[] stringListe;
public IterableSelbstKorrekt(int size) {
stringListe = new String[size];
}
private IterableSelbstKorrekt(String[] stringListe) {
this.stringListe = stringListe;
}
public Iterator<String> iterator() {
return new IterableSelbstKorrekt(stringListe);
}
public static void main(String[] args) {
String[] strings = new String[] { "A", "B", "C", "D" };
IterableSelbstKorrekt liste = new IterableSelbstKorrekt(strings);
for (String string : liste) {
System.out.println(string);
}
}
private int pos = 0;
public boolean hasNext() {
return (pos < stringListe.length);
}
public String next() {
return stringListe[pos++];
}
public void remove() {
throw new UnsupportedOperationException();
}
}

View File

@ -0,0 +1,41 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.maps;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MapBeispiel {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("go", "gehen");
map.put("walk", "gehen");
map.put("sleep", "schlafen");
map.put("learn", "lernen");
System.out.println(map); // --> {learn=lernen, sleep=schlafen, walk=gehen, go=gehen}
System.out.println(map.get("go")); // --> gehen
System.out.println(map.get("walk")); // --> gehen
System.out.println(map.get("learn")); // --> lernen
System.out.println(map.keySet()); // --> [learn, sleep, walk, go]
System.out.println(map.values()); // --> [lernen, schlafen, gehen, gehen]
Set<Map.Entry<String, String>> entrySet = map.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
String key = entry.getKey();
String value = entry.getValue();
System.out.printf("%s engl. fuer %s%n", key, value);
}
}
}

View File

@ -0,0 +1,26 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.maps;
import java.util.HashMap;
import java.util.Map;
public class MapBeispiel2 {
public static void main(String[] args) {
Map<Personalnummer, Mitarbeiter> map = new HashMap<>();
Mitarbeiter meier = new Mitarbeiter("Meier", 1200.00);
Mitarbeiter mueller = new Mitarbeiter("Mueller", 2400.00);
Mitarbeiter schulze = new Mitarbeiter("Schulze", 1200.00);
map.put(new Personalnummer("4711"), meier);
map.put(new Personalnummer("4242"), mueller);
map.put(new Personalnummer("0007"), schulze);
System.out.println(map.containsKey(new Personalnummer("0007"))); // --> true
System.out.println(map.containsValue(meier)); // --> true
}
}

View File

@ -0,0 +1,23 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.maps;
import java.util.HashMap;
import java.util.Map;
public class MapBeispiel3 {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("gehen", "go");
map.put("gehen", "walk");
map.put("schlafen", "sleep");
map.put("lernen", "learn");
System.out.println(map);
}
}

View File

@ -0,0 +1,68 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.maps;
import java.util.Date;
public class Mitarbeiter {
public String name;
public double gehalt;
public Date geburtsdatum;
public Mitarbeiter(String name, double gehalt, Date geburtsdatum) {
super();
this.name = name;
this.gehalt = gehalt;
this.geburtsdatum = geburtsdatum;
}
public Mitarbeiter(String name, double gehalt) {
super();
this.name = name;
this.gehalt = gehalt;
}
public boolean equals(Object o) {
if (o == null) {
return false;
}
else if (o == this) {
return true;
}
else if (o instanceof Mitarbeiter) {
Mitarbeiter mi = (Mitarbeiter) o;
return mi.name.equals(name)
&& mi.gehalt == gehalt
&& mi.geburtsdatum.equals(geburtsdatum);
}
else {
return false;
}
}
public int hashCode() {
return name.hashCode()
^ (int) Double.doubleToLongBits(gehalt)
^ geburtsdatum.hashCode();
}
public void doIt(Mitarbeiter m) {
System.out.println(m + " hat ein Gehalt von " + gehalt);
System.out.println(m.toString() + " hat ein Gehalt von " + Double.toString(gehalt));
}
public String toString() {
return "Mitarbeiter [name: " + name + ", "
+ "gehalt: " + gehalt + ", "
+ "geburtsdatum " + geburtsdatum + "]";
}
public static void main(String[] args) {
Mitarbeiter m = new Mitarbeiter("Franz Meier", 5000.00, new Date(new Date().getTime() - 1000L*1000*1000*1000));
m.doIt(m);
}
}

View File

@ -0,0 +1,45 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.maps;
public class Personalnummer {
private String nummer;
@Override
public String toString() {
return "Personalnummer [" + nummer + "]";
}
public Personalnummer(String nummer) {
super();
this.nummer = nummer;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((nummer == null) ? 0 : nummer.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Personalnummer other = (Personalnummer) obj;
if (nummer == null) {
if (other.nummer != null)
return false;
} else if (!nummer.equals(other.nummer))
return false;
return true;
}
}

View File

@ -0,0 +1,36 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.sorting;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class ReverseComparator implements Comparator<String> {
public int compare(String o1, String o2) {
return o1.compareTo(o2) * -1;
}
}
public class ListSortierung {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Seeler");
list.add("Mueller");
list.add("Zander");
list.add("Beckenbauer");
list.add("Schumacher");
Collections.sort(list);
System.out.println(list);
Collections.sort(list, new ReverseComparator());
System.out.println(list);
}
}

View File

@ -0,0 +1,27 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.sorting;
import java.util.SortedSet;
import java.util.TreeSet;
public class SortedSetDemo {
public static void main(String[] args) {
SortedSet<String> set = new TreeSet<>();
set.add("Seeler");
set.add("Mueller");
set.add("Zander");
set.add("Beckenbauer");
set.add("Schumacher");
System.out.printf("Elemente: %s%n", set);
System.out.printf("Erstes Element: %s%n", set.first());
System.out.printf("Letztes Element: %s%n", set.last());
}
}

View File

@ -0,0 +1,31 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.sorting.comparable;
public class Student implements Comparable<Student> {
private int matrikelNummer;
private String name;
public Student(int matrikelNummer, String name) {
this.matrikelNummer = matrikelNummer;
this.name = name;
}
public int compareTo(Student o) {
if (o.matrikelNummer == matrikelNummer) {
return 0;
}
else if (o.matrikelNummer > matrikelNummer) {
return -1;
}
else {
return 1;
}
}
public String toString() {
return matrikelNummer + " - " + name;
}
}

View File

@ -0,0 +1,39 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.sorting.comparable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class StudentDemo {
public static void main(String[] args) {
{
Set<Student> studenten = new TreeSet<>();
studenten.add(new Student(4411, "Franz Müller"));
studenten.add(new Student(5711, "Albert Meier"));
studenten.add(new Student(4711, "Xaver Meier"));
for (Student student : studenten) {
System.out.println(student);
}
}
{
List<Student> studenten = new ArrayList<>();
studenten.add(new Student(4411, "Franz Müller"));
studenten.add(new Student(5711, "Albert Meier"));
studenten.add(new Student(4711, "Xaver Meier"));
Collections.sort(studenten);
for (Student student : studenten) {
System.out.println(student);
}
}
}
}

View File

@ -0,0 +1,19 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.sorting.comparator;
public class Student {
int matrikelNummer;
String name;
public Student(int matrikelNummer, String name) {
this.matrikelNummer = matrikelNummer;
this.name = name;
}
public String toString() {
return matrikelNummer + " - " + name;
}
}

View File

@ -0,0 +1,21 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.sorting.comparator;
import java.util.Comparator;
public class StudentComparator implements Comparator<Student> {
public int compare(Student o1, Student o2) {
if (o2.matrikelNummer == o1.matrikelNummer) {
return 0;
}
else if (o2.matrikelNummer > o1.matrikelNummer) {
return -1;
}
else {
return 1;
}
}
}

View File

@ -0,0 +1,42 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.sorting.comparator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class StudentDemo {
public static void main(String[] args) {
{
Set<Student> studenten = new TreeSet<Student>(new StudentComparator());
studenten.add(new Student(4411, "Franz Müller"));
studenten.add(new Student(5711, "Albert Meier"));
studenten.add(new Student(4711, "Xaver Meier"));
for (Student student : studenten) {
System.out.println(student);
}
}
{
List<Student> studenten = new ArrayList<>();
studenten.add(new Student(4411, "Franz Müller"));
studenten.add(new Student(5711, "Albert Meier"));
studenten.add(new Student(4711, "Xaver Meier"));
Collections.sort(studenten, new StudentComparator());
for (Student student : studenten) {
System.out.println(student);
}
}
}
}

View File

@ -0,0 +1,34 @@
/*
* (c) 2009 Thomas Smits
*/
package pr2.collections.threads;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
public class ConcurrentModificationException {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
Collections.addAll(list, "A", "B", "C", "D", "E", "X", "F");
for (String element : list) {
if ("X".equals(element)) {
list.remove(element);
}
}
ListIterator<String> it = list.listIterator();
while (it.hasNext()) {
String element = it.next();
if ("X".equals(element)) {
it.remove();
}
}
}
}

View File

@ -0,0 +1,118 @@
package pr2.ds.avl;
class Node {
int key, height;
Node left, right;
public Node(int key) {
this.key = key;
height = 1;
}
}
public class AVLTree {
Node root;
int height(Node N) {
if (N == null)
return 0;
return N.height;
}
int max(int a, int b) {
return (a > b) ? a : b;
}
Node rightRotate(Node y) {
Node x = y.left;
Node T2 = x.right;
x.right = y;
y.left = T2;
y.height = max(height(y.left), height(y.right)) + 1;
x.height = max(height(x.left), height(x.right)) + 1;
return x;
}
Node leftRotate(Node x) {
Node y = x.right;
Node T2 = y.left;
y.left = x;
x.right = T2;
x.height = max(height(x.left), height(x.right)) + 1;
y.height = max(height(y.left), height(y.right)) + 1;
return y;
}
int getBalance(Node N) {
if (N == null)
return 0;
return height(N.left) - height(N.right);
}
Node insert(Node node, int key) {
if (node == null)
return (new Node(key));
if (key < node.key)
node.left = insert(node.left, key);
else if (key > node.key)
node.right = insert(node.right, key);
else
return node;
node.height = 1 + max(height(node.left),
height(node.right));
int balance = getBalance(node);
if (balance > 1 && key < node.left.key)
return rightRotate(node);
if (balance < -1 && key > node.right.key)
return leftRotate(node);
if (balance > 1 && key > node.left.key) {
node.left = leftRotate(node.left);
return rightRotate(node);
}
if (balance < -1 && key < node.right.key) {
node.right = rightRotate(node.right);
return leftRotate(node);
}
return node;
}
void preOrder(Node node) {
if (node != null) {
System.out.print(node.key + " ");
preOrder(node.left);
preOrder(node.right);
}
}
public static void main(String[] args) {
AVLTree tree = new AVLTree();
/* Constructing tree given in the above figure */
tree.root = tree.insert(tree.root, 10);
tree.root = tree.insert(tree.root, 20);
tree.root = tree.insert(tree.root, 30);
tree.root = tree.insert(tree.root, 40);
tree.root = tree.insert(tree.root, 50);
tree.root = tree.insert(tree.root, 25);
System.out.println("Preorder traversal" +
" of constructed tree is : ");
tree.preOrder(tree.root);
}
}

View File

@ -0,0 +1,66 @@
package pr2.ds.bt;
class Node {
int data;
Node left;
Node right;
public Node(int item) {
data = item;
left = right = null;
}
}
public class BinaryTree {
// Wurzel des Baums
Node root;
public BinaryTree() {
root = null;
}
public void insert(int key) {
root = insertRec(root, key);
}
private Node insertRec(Node root, int key) {
if (root == null) {
root = new Node(key);
return root;
}
if (key < root.data)
root.left = insertRec(root.left, key);
else if (key > root.data)
root.right = insertRec(root.right, key);
return root;
}
public void inorder() {
inorderRec(root);
}
void inorderRec(Node root) {
if (root != null) {
inorderRec(root.left);
System.out.println(root.data);
inorderRec(root.right);
}
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);
tree.inorder();
}
}

View File

@ -0,0 +1,94 @@
package pr2.ds.bt;
import java.util.LinkedList;
import java.util.function.Consumer;
public class SimpleTree {
private static class Node {
private Node left;
private Node right;
private String data;
public Node(String data, Node left, Node right) {
this.left = left;
this.right = right;
this.data = data;
}
public Node(String data) {
this.left = null;
this.right = null;
this.data = data;
}
}
private Node root;
public SimpleTree(Node root) {
this.root = root;
}
public void preorder(Consumer<String> f) {
preorder(f, this.root);
}
public void preorder(Consumer<String> f, Node node) {
if (node == null) return;
f.accept(node.data); // Aktion auf dem Knoten ausführen
preorder(f, node.left); // Linker Teilbaum
preorder(f, node.right); // Rechter Teilbaum
}
public void inorder(Consumer<String> f) {
inorder(f, this.root);
}
public void inorder(Consumer<String> f, Node node) {
if (node == null) return;
preorder(f, node.left); // Linker Teilbaum
f.accept(node.data); // Aktion auf dem Knoten ausführen
preorder(f, node.right); // Rechter Teilbaum
}
public void postorder(Consumer<String> f) {
postorder(f, this.root);
}
public void postorder(Consumer<String> f, Node node) {
if (node == null) return;
postorder(f, node.left); // Linker Teilbaum
postorder(f, node.right); // Rechter Teilbaum
f.accept(node.data); // Aktion auf dem Knoten ausführen
}
public void levelorder(Consumer<String> f) {
var list = new LinkedList<Node>();
list.add(root);
while (!list.isEmpty()) {
Node n = list.pollFirst();
f.accept(n.data); // Aktion ausführen
if (n.left != null) {
list.add(n.left);
}
if (n.right != null) {
list.add(n.right);
}
}
}
public static void main(String[] args) {
SimpleTree t = new SimpleTree(
new Node("A",
new Node("B", new Node("D"), new Node("E")),
new Node("C", new Node("F"), new Node("G"))));
System.out.print("Pre-Order: ");
t.preorder(System.out::print);
System.out.print("\nIn-Order: ");
t.inorder(System.out::print);
System.out.print("\nPost-Order: ");
t.postorder(System.out::print);
System.out.print("\nLevel-Order: ");
t.levelorder(System.out::print);
}
}

View File

@ -0,0 +1,55 @@
package pr2.ds.buffer;
public class RingBuffer<T> {
private T[] elements;
private int head = 0;
private int tail = 0;
private int size = 0;
public RingBuffer(int capacity) {
elements = (T[]) new Object[capacity];
}
// Element hinzufügen
public void add(T element) {
if (size == elements.length) {
head = (head + 1) % elements.length;
} else {
size++;
}
elements[tail] = element;
tail = (tail + 1) % elements.length;
}
// erstes Element zurückgeben
public T first() {
if (size == 0) {
return null;
}
return elements[head];
}
// letztes Element zurückgeben
public T last() {
if (size == 0) {
return null;
}
return elements[(tail - 1 + elements.length) % elements.length];
}
// Puffer leer?
public boolean isEmpty() {
return size == 0;
}
// Puffer voll?
public boolean isFull() {
return size == elements.length;
}
// Anzahl der Elemente im Puffer
public int size() {
return size;
}
}

View File

@ -0,0 +1,54 @@
package pr2.ds.graph;
import java.util.LinkedList;
class Graph {
private int V; // Anzahl der Knoten
private LinkedList<Integer> adj[]; // Adjazenzliste
Graph(int v) {
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
void addEdge(int v, int w) {
adj[v].add(w);
adj[w].add(v);
}
void DFS(int v, boolean visited[]) {
visited[v] = true;
System.out.print(v + " ");
for (Integer neighbour : adj[v]) {
if (!visited[neighbour])
DFS(neighbour, visited);
}
}
void DFS() {
boolean visited[] = new boolean[V];
for (int i = 0; i < V; i++) {
if (!visited[i]) {
DFS(i, visited);
}
}
}
public static void main(String args[]) {
Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
System.out.println("Following is Depth First Traversal");
g.DFS();
}
}

View File

@ -0,0 +1,53 @@
package pr2.ds.hash;
import java.util.LinkedList;
public class BetterHashTable {
private static final int SIZE = 10;
private final LinkedList[] buckets = new LinkedList[SIZE];
public BetterHashTable() {
for (int i = 0; i < SIZE; i++) {
buckets[i] = new LinkedList();
}
}
public int idx(String s) {
return Math.abs(s.hashCode()) % SIZE;
}
public void add(String s) {
buckets[idx(s)].add(s);
}
public void remove(String s) {
buckets[idx(s)].remove(s);
}
public boolean contains(String s) {
return buckets[idx(s)].contains(s);
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < SIZE; i++) {
sb.append(String.format("[%d]: %s\n", i,
buckets[i] == null ? "" : buckets[i]));
}
return sb.toString();
}
public static void main(String[] args) {
BetterHashTable sh = new BetterHashTable();
sh.add("Januar");
sh.add("Februar");
sh.add("März");
sh.add("April");
sh.add("Mai");
System.out.println(sh.toString());
System.out.println(sh.contains("Februar")); // -> true
System.out.println(sh.contains("Januar")); // -> true
}
}

View File

@ -0,0 +1,51 @@
package pr2.ds.hash;
import java.util.LinkedList;
public class HashTable {
private int SIZE = 10;
private LinkedList<Node>[] table;
HashTable() {
table = new LinkedList[SIZE];
for (int i = 0; i < SIZE; i++)
table[i] = new LinkedList();
}
public void put(int key, int value) {
int index = hash(key);
table[index].add(new Node(key, value));
}
public int get(int key) {
int index = hash(key);
for (Node node : table[index])
if (node.key == key)
return node.value;
return -1;
}
public void remove(int key) {
int index = hash(key);
for (Node node : table[index])
if (node.key == key) {
table[index].remove(node);
break;
}
}
private int hash(int key) {
return key % SIZE;
}
private static class Node {
int key;
int value;
public Node(int key, int value) {
this.key = key;
this.value = value;
}
}
}

View File

@ -0,0 +1,45 @@
package pr2.ds.hash;
public class SimpleHashTable {
private static final int SIZE = 10;
private final String[] buckets = new String[SIZE];
public int idx(String s) {
return Math.abs(s.hashCode()) % SIZE;
}
public void add(String s) {
buckets[idx(s)] = s;
}
public void remove(String s) {
buckets[idx(s)] = null;
}
public boolean contains(String s) {
return s.equals(buckets[idx(s)]);
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < SIZE; i++) {
sb.append(String.format("[%d]: %s\n", i,
buckets[i] == null ? "" : buckets[i]));
}
return sb.toString();
}
public static void main(String[] args) {
SimpleHashTable sh = new SimpleHashTable();
sh.add("Januar");
sh.add("Februar");
sh.add("März");
sh.add("April");
sh.add("Mai");
System.out.println(sh.toString());
System.out.println(sh.contains("Februar"));
System.out.println(sh.contains("Januar"));
}
}

View File

@ -0,0 +1,24 @@
package pr2.ds.liste;
public class ArrayIterator {
private final int[] array;
private int pos;
public ArrayIterator(int[] array) {
this.array = array.clone();
pos = 0;
}
public boolean hasNext() {
return pos < array.length;
}
public int next() {
return array[pos++]; // ArrayIndexOutOfBoundsException
}
public void reset() {
pos = 0;
}
}

View File

@ -0,0 +1,14 @@
package pr2.ds.liste;
public class ArrayIteratorTest {
public static void main(String[] args) {
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8 };
ArrayIterator ai1 = new ArrayIterator(array);
ArrayIterator ai2 = new ArrayIterator(array);
while (ai1.hasNext()) {
System.out.println(ai1.next());
}
}
}

View File

@ -0,0 +1,112 @@
package pr2.ds.liste;
class DoubleLinkedList implements IntList {
private static class Node {
int data;
Node next;
Node prev;
Node(int data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
Node head;
Node tail;
public void append(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
tail = newNode;
return;
}
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
}
public void prepend(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
tail = newNode;
return;
}
newNode.next = head;
head.prev = newNode;
head = newNode;
}
public void deleteWithValue(int data) {
if (head == null) {
return;
}
if (head.data == data) {
head = head.next;
head.prev = null;
return;
}
Node current = head;
while (current.next != null) {
if (current.next.data == data) {
current.next = current.next.next;
if (current.next != null) {
current.next.prev = current;
}
return;
}
current = current.next;
}
}
public void printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[ ");
Node current = head;
while (current != null) {
sb.append(current.data);
current = current.next;
if (current != null) {
sb.append(", ");
}
}
sb.append(" ]");
return sb.toString();
}
public int size() {
Node current = head;
int count = 0;
while (current != null) {
count++;
current = current.next;
}
return count;
}
}

View File

@ -0,0 +1,9 @@
package pr2.ds.liste;
public interface IntList {
void append(int data);
void prepend(int data);
int size();
}

Some files were not shown because too many files have changed in this diff Show More