int i = 0;
String alphabet = "abcdefghijklmnopqrstuvwxyz";
char letter = alphabet.charAt(i);
Letter a = new Letter(i,letter); Letter b = new Letter(i,letter); Letter c = new Letter(i,letter); Letter d = new Letter(i,letter); //...
是否有更短的方式让名称在字母表中循环?
最佳答案
假设 Java 8(引入流后),如果我们可以稍微简化 Letter
构造函数并采取一个微小的假设 - i
,事情就会变得非常容易代码中的变量只是字母的索引 - 在这种情况下,您可以计算它而无需将其传递给构造函数(c - 'a'
),因此我将在构造函数中省略它- 它增加了很多不必要的噪音。
为了使我的答案更完整,我们假设这是我们将使用的 Letter
类:
public class Letter {
char c; int index;
public Letter(int c) {
this.c = (char) c;
this.index = c - 'a';
}
}
整个事情可以在一行内完成:
List<Letter> l = "abcdefghijklmnopqrstuvwxyz".chars().mapToObj(Letter::new).collect(Collectors.toList());
注释的代码如下所示:
"abcdefghijklmnopqrstuvwxyz" // Take the alphabet string
.chars() // Turn the string into IntStream
.mapToObj(Letter::new) // Map all the characters into Letter constructor,
// effectively transposing into stream of Letters
.collect(Collectors.toList()); // Finally, collect all the Letters from the stream
// into a list.
或者,如果您想获取数组,可以使用 .toArray();
而不是 .collect(...);
关于java - 使用变量 String 或 char 作为对象名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60362616/