java – 使用LinkedList对名称进行排序并将其存储到Array单元格
作者:互联网
因此,我们的想法是获取一个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
有没有更有效的方法来做到这一点?
解决方法:
假设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);
}
标签:java,arrays,singly-linked-list 来源: https://codeday.me/bug/20190706/1393231.html