假設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()可能會有用。 –