英文:
Add alphabets to List Java
问题
我想创建一个包含每个字母出现5次的字母表列表。我尝试了一段代码,它有效地工作了。
public class AlphabetsTest {
public static void main(String[] args) {
List<Character> alphabetList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
char chr = 'a';
if (i == 1)
chr = 'b';
if (i == 2)
chr = 'c';
for (int j = 0; j < 5; j++) {
alphabetList.add(chr);
}
}
}
}
但是,如果要添加更多字母,我将不得不添加多个条件语句。有没有更好的方法来避免这种情况。
英文:
I want create a list with alphabets with each alphabets for 5 times. I tried a code and it worked,
public class AlphabetsTest {
public static void main(String[] args) {
List<Character> alphabetList = new ArrayList<>();
for (int i=0; i<3; i++){
char chr='a';
if (i==1)
chr = 'b';
if (i==2)
chr = 'c';
for (int j=0; j<5; j++){
alphabetList.add(chr);
}
}
}
}
But I would have to add multiple if conditions for more alphabets. Is there any better way to avoid it.
答案1
得分: 1
你可以像下面这样使用char
循环:
List<Character> alphabetList = new ArrayList<>();
for (char chr = 'a'; chr <= 'c'; chr++) {
for (int j = 0; j < 5; j++) {
alphabetList.add(chr);
}
}
你还可以使用Collections.nCopies
来避免内部循环:
for (char chr = 'a'; chr <= 'c'; chr++) {
alphabetList.addAll(Collections.nCopies(5, chr));
}
英文:
You can use char
loop as below,
List<Character> alphabetList = new ArrayList<>();
for(char chr = 'a'; chr <= 'c'; chr++){
for (int j=0; j<5; j++){
alphabetList.add(chr);
}
}
You may also want to use, Collections.nCopies
to avoid inner loop,
for(char chr = 'a'; chr <= 'c'; chr++){
alphabetList.addAll(Collections.nCopies(5, chr));
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论