2016-11-18 88 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类来满足您的需求。 –

相关问题