Skip to content

Instantly share code, notes, and snippets.

@cokeSchlumpf
Created February 27, 2013 09:24
Show Gist options
  • Save cokeSchlumpf/5046595 to your computer and use it in GitHub Desktop.
Save cokeSchlumpf/5046595 to your computer and use it in GitHub Desktop.
String Switch
package de.michaelwellner.edu.stringswitch;
public class StringSwitch {
private static final String HALLO = "Hallo";
private static final String GUT = "Gut";
private static final String SCHOENEN_TAG = "Schönen Tag noch!";
private static final String CIAO = "Ciao";
private static final String TSCHUESS = "Tschüss";
private static final String HALLO_WIE = "Hallo, wie geht es dir?";
private static final String PRIMA = "Das finde ich prima!";
private static final String DANKE = "Danke dir auch!";
private static final String BIS_BALD = "Bis bald!";
private static final String NOPE = "Leider habe ich dich nicht verstanden.";
private static final Console C = new Console();
private static interface Output {
public void println(String s);
}
private static class Console implements Output {
@Override
public void println(String s) {
System.out.println(s);
}
}
private static class Kummerkasten implements Output {
@Override
public void println(String s) {
// Und ab nach /dev/null ...
}
}
public StringSwitch(final String... args) {
for (int i = 0; i < 10; test(i++));
}
private void test(int num, final String ... args) {
C.println("Testlauf " + num);
long j6 = benchmark(new Runnable() {
@Override
public void run() {
java6(new Kummerkasten(), args);
}
});
C.println("Java 6: " + j6);
long j7 = benchmark(new Runnable() {
@Override
public void run() {
java7(new Kummerkasten(), args);
}
});
C.println("Java 7: " + j7);
C.println("Diff: " + (j7 - j6));
C.println("");
}
private long benchmark(Runnable runnable) {
long start = System.currentTimeMillis();
for (long i = 0; i < 500_000_000; i++) {
runnable.run();
}
long end = System.currentTimeMillis();
return end - start;
}
private void java7(Output out, String... args) {
for (String arg : args) {
switch (arg) {
case HALLO:
out.println(HALLO_WIE);
break;
case GUT:
out.println(PRIMA);
break;
case SCHOENEN_TAG:
out.println(DANKE);
case CIAO:
case TSCHUESS:
out.println(BIS_BALD);
break;
default:
out.println(NOPE);
}
}
}
private void java6(Output out, String... args) {
for (String arg : args) {
if (arg.equals(HALLO)) {
out.println(HALLO_WIE);
} else if (arg.equals(GUT)) {
out.println(PRIMA);
} else if (arg.equals(SCHOENEN_TAG)) {
out.println(DANKE);
out.println(BIS_BALD);
} else if (arg.equals(CIAO) || arg.equals(TSCHUESS)) {
out.println(BIS_BALD);
} else {
out.println(NOPE);
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
new StringSwitch(HALLO, GUT, CIAO);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment