Search code examples
javaiteratortrie

Can you use an iterator on an array?


This isn't an easy question to write, there are a lot of angles to it. I'm trying to write a very basic Trie in Java to help myself understand the concept and its uses. I'm not entirely sure I'm doing it right, but regardless I'm having issues with the following:

    for(char c: value.toCharArray()){
    TrieNode nodeChecker = rootNode.checkValue(c);    //checks currentNode to see if characters are keys in HashMap
    if(nodeChecker == null){
        rootNode = rootNode.add(c);     //if not, adds the character as a key, returns another TrieNode
    }

Basically what I'm doing here, is adding the word "sample" to a tree. I create a HashMap, with the key being the character and the value being another HashMap. (so nested hash maps, which is where I'm not entirely sure this is a proper Trie, but nevermind that).

The problem I'm having is that I want to stop on the final value of value.toCharArray (whatever the last character c is). If I don't stop on the last character it continues to add nested HashMaps and never actually puts the word in. I was trying to create an iterator and use the hasNext() function but nothing I try works.

Iterator<Character> iter = value.toCharArray().iterator(); //"cannot invoke iterator on the array type char[]"

I can't get the iterator to go through the array, are iterators not compatible with arrays? Only Lists or arraylists? If this is the case, is there an easy way to get a character array into a list so that I CAN use the hasNext() capability?


Solution

  • You will have to loop to convert the array to a list, since Arrays.asList(value.toCharArray()) will produce a List<char[]>:

    List<Character> characters = new ArrayList<Character>();
    for (char c : value.toCharArray()) {
        characters.add(c);
    }