使用变量String或char作为对象名称


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(...);

最新更新