2016-11-18 21 views
4

所以我們的想法是獲得一個輸入爲String(名稱是特定的),然後將它存儲在一個大小爲26的Array中以將其存儲到其相應的單元格中。排序是這樣的:以'A'開頭的名稱到單元格0,以'B'開頭的名稱到單元格1,依此類推。現在,單元格包含一個LinkedList,其中名稱按字母順序重新排序。使用LinkedList對名稱進行排序並將它們存儲到Array單元

到目前爲止,我所做的方法是使用開關盒。

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 

有沒有更有效的方法來做到這一點?

+5

有你試過'AuthorList [nD - 'A'] = iN;'? – OldCurmudgeon

+0

@OldCurmudgeon不,謝謝。我甚至不知道你可以這樣做。 – Helquin

+0

但是你需要以某種方式保護ArrayOutOfBoundException。例如,捕捉它並拋出關於大寫首字母要求的適當消息的新IllegalArgumentException。另外iN.trim()可能會有用。 –

回答

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); 
} 
+0

列表不是通用iirc還是應該是ArrayList?無論哪種方式,我都會嘗試用你的代碼模擬我的代碼,看看它是否可行,然後我可以接受這個答案。 – Helquin

+0

我不確定AuthorList是什麼,以及如何向它添加數據,但我確定將字符串賦給AuthorList [x]''會失敗,所以我已經改變它以使其正常工作以用於測試目的。當然,您應該使用AuthorList類來滿足您的需求。 –

相關問題