Helquin Helquin - 20 days ago 5
Java Question

Sorting names and storing them to an Array cell with LinkedList

So the idea is to get an input which is a

String
(a name to be specific), then store it in an
Array
with the size of 26 to its respective cell. The sorting goes this way: names that start with 'A' goes to cell 0, names that start with 'B' goes to cell 1 and so on. Now, a cell contains a
LinkedList
where the names are sorted again alphabetically.

So far, the approach I made is by using the switch case.

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


is there a more efficient way to do this?

Answer

Assuming that AuthorList class may look like this:

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();
    }
}

I'd make it like this:

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");
    }
}

And additional main method for test purposes:

public static void main (String[] args){
    AuthorList[] aL = new AuthorList[26];
    addDataAList(aL, " dudeman");
    for (AuthorList list : aL) System.out.println(list);
}