Repeat a string n times without a loop.
Porównanie kodu
✕ Java 8
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) {
sb.append("abc");
}
String result = sb.toString();
✓ Java 11+
String result = "abc".repeat(3); // "abcabcabc"
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
One-liner
Replace 5 lines of StringBuilder code with one call.
Optimized
Internal implementation is optimized for large repeats.
Clear intent
repeat(3) immediately conveys the purpose.
Stare podejście
StringBuilder Loop
Nowoczesne podejście
repeat()
Od JDK
11
Poziom trudności
Początkujący
Wsparcie JDK
String.repeat()
Dostępne
Widely available since JDK 11 (Sept 2018)
Jak to działa
String.repeat(int) returns the string concatenated with itself n times. Handles edge cases: repeat(0) returns empty string, repeat(1) returns the same string.
Powiązana dokumentacja