Skip to content

Instantly share code, notes, and snippets.

@MuffinTheMan
Last active May 6, 2024 14:46
Show Gist options
  • Save MuffinTheMan/dc16876f98af75fa4186ede0a5cc8176 to your computer and use it in GitHub Desktop.
Save MuffinTheMan/dc16876f98af75fa4186ede0a5cc8176 to your computer and use it in GitHub Desktop.
Java snippets for reference
// Two ways to "for each / foreach"
String letters = "abcdefghijklmnopqrstuvwxyz";
char[] letterArr = letters.toCharArray();
for (int i = 0; i < letterArr.length; i++) {
System.out.println(letterArr[i]);
}
// Above and below are the same in result
for (char c : letterArr) {
System.out.println(c);
}
// ===== ===== ===== ===== ===== ===== //
// Ternary (short-form if/else)
if (x == null) {
y = 0;
} else {
y = x;
}
// Above and below are the same in result
y = ((x == null) ? 0 : x);
//region Java Records
// Shallowly immutable class
class LabeledStringList {
private final String label;
private final List<String> list;
public LabeledStringList(final String label, final List<String> list) {
this.label = label;
this.list = list;
}
public String label() {
return label;
}
public List<String> list() {
return list;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof LabeledStringList that)) return false;
return Objects.equals(label, that.label) && Objects.equals(list, that.list);
}
@Override
public int hashCode() {
return Objects.hash(label, list);
}
@Override
public String toString() {
return String.format(
"%s[label=%s, list=%s]",
getClass().getSimpleName(),
label,
list
);
}
}
// As a record
record LabeledStringList(String label, List<String> list) {
}
//endregion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment