因此,我们的想法是获得一个String
(特定名称)的输入,然后将其存储在大小为26的Array
中。排序方式是这样的:名称以' A'开头。转到单元格0,名称以' B'转到单元格1,依此类推。现在,单元格包含LinkedList
,其中名称按字母顺序再次排序。
到目前为止,我所采用的方法是使用开关盒。
private void addDataAList(AuthorList[] aL, String iN) {
char nD = Character.toUpperCase(iN.charAt(0));
switch(nD){
case 'A':
AuthorList[0] = iN;
break;
case 'B':
AuthorList[1] = iN;
break;
//and so on
}
}//addData
有更有效的方法吗?
答案 0 :(得分:1)
假设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);
}