假设AuthorList类可能是这样的:
private class AuthorList{
private LinkedList<String> nameList;
public AuthorList() {
}
public AuthorList(LinkedList<String> nameList) {
this.nameList = nameList;
}
public LinkedList<String> getNameList() {
return nameList;
}
public void setNameList(LinkedList<String> nameList) {
this.nameList = nameList;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("AuthorList{");
sb.append("nameList=").append(nameList);
sb.append('}');
return sb.toString();
}
}
我会做这样的:
private static void addDataAList(AuthorList[] aL, String iN) {
int index = Character.toUpperCase(iN.trim().charAt(0)) - 'A';
try {
AuthorList tmpAuthorList = aL[index];
if(tmpAuthorList == null) aL[index] = tmpAuthorList = new AuthorList(new LinkedList<>());
if(tmpAuthorList.getNameList() == null) tmpAuthorList.setNameList(new LinkedList<>());
tmpAuthorList.getNameList().add(iN);
} catch (ArrayIndexOutOfBoundsException aioobe){
throw new IllegalArgumentException("Name should start with character A - Z");
}
}
和额外的主要方法用于测试目的:
public static void main (String[] args){
AuthorList[] aL = new AuthorList[26];
addDataAList(aL, " dudeman");
for (AuthorList list : aL) System.out.println(list);
}
有你试过'AuthorList [nD - 'A'] = iN;'? – OldCurmudgeon
@OldCurmudgeon不,谢谢。我甚至不知道你可以这样做。 – Helquin
但是你需要以某种方式保护ArrayOutOfBoundException。例如,捕捉它并抛出关于大写首字母要求的适当消息的新IllegalArgumentException。另外iN.trim()可能会有用。 –