Sort names and save them in an Array cell using LinkedList

So, the idea is to get the input, which is String(a specific name), and then save it in Arraysize 26 to the appropriate cell. Sorting is as follows: names starting with "A" go to cell 0, names starting with "B" go to cell 1 and so on. The cell now contains LinkedListwhere the names are sorted alphabetically.

So far, the approach I have made is to use a switch enclosure.

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?

+4
source share
1 answer

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

Source: https://habr.com/ru/post/1661205/


All Articles