问题
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:
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));
}
来源:https://stackoverflow.com/questions/61027316/add-alphabets-to-list-java