bond007
bond007

Reputation: 41

Convert ArrayList to LinkedList

If I want to change this implementation from ArrayList to LinkedList do I just have to change

ArrayList<Character> characters = new ArrayList<Character>();

to

LinkedList<Character> characters = new List<Character>();

Or how do I do this?

ArrayList<Character> characters = new ArrayList<Character>();
try {
    while((str = bufferedReader.readLine()) != null){
        char [] characterArray = str.toCharArray();

        for (int i = 0; i <  characterArray.length; i++){

            characters.add(characterArray[i]);
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}
char [] patternArray = phrase.toCharArray();
ArrayList<Character> pattern = new ArrayList<Character>();
for (int i = 0; i <  patternArray.length; i++) {

    pattern.add(patternArray[i]);
}

Upvotes: 3

Views: 13086

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

This code offers a nice illustration to why programming to interfaces is a good thing. You keep using this declaration pattern:

ArrayList<Character> characters = new ArrayList<Character>();

If you wish to make characters a linked list, you would have to make changes in two places. If you used interface name for the declaration, like this

List<Character> characters = new ArrayList<Character>();

the rest of your code would continue working, but you would be able to make a single change to convert to LinkedList:

List<Character> characters = new LinkedList<Character>();

Same goes for the declaration of your pattern variable.

It is too slow and uses too much memory

Of course it does! Long linked lists take significantly more memory, so it's impractical to use them for character-by-character representations. Generally, conversions of strings to character lists is practical only when you deal with a small number of short strings. In other situations you would be better off with String objects, or StringBuilder objects if you need mutability.

Upvotes: 9

Related Questions