0

Back ground: I am pairing up two pieces of data, both Strings, into an ArrayList. Therefore I am storing the paired data into an object, and then storing this object into an ArrayList. I have a text file that for each word, I am assigning a number to. The paired data is then word-number (but I have typed them both as String). I do not know how many objects I will need for any given file size.

How do I set up a logic to iterate through the text file and populate my ArrayList. This is what I have done so far:

The : PredictivePrototype.wordToSignature(aWord)// converts the word into a number signature e.g "4663" for a word like "home"

public class ListDictionary {

    private static ArrayList<WordSig> dictionary;

    public ListDictionary() throws FileNotFoundException {

        File theFile = new File("words");
        Scanner src = new Scanner(theFile);

        while (src.hasNext()) {
            String aWord = src.next();
            String sigOfWord = PredictivePrototype.wordToSignature(aWord);

            // assign each word and its corresponding signature into attribute
            // of an object(p) of class WordSig.
            //WordSig p1 = new WordSig(aWord, sigOfWord);

            //Then add this instance (object) of class Wordsig into ArrayList<WordSig>
            dictionary.add(new WordSig(aWord, sigOfWord));
        }
        src.close();


    }

Other class to which paired data is stored:

public class WordSig {

    private String words;
    private String signature;

    public WordSig(String words, String signature) {
        this.words=words;
        this.signature=signature;

    }

}
Ashot Karakhanyan
  • 2,804
  • 3
  • 23
  • 28

1 Answers1

0

Your code seems to be OK. With ArrayList you can add as many elements as you want (by using add() function).

Here is an example:

import java.util.ArrayList;

public class ListDictionary {

    public class WordSig {
        private String words;
        private String signature;

        public WordSig(String words, String signature) {
            this.words=words;
            this.signature=signature;
        }
        public String getWords() {
            return words;
        }
        public String getSignature() {
            return signature;
        }
    }

    private static ArrayList<WordSig> dictionary = new ArrayList<WordSig>();

    public ListDictionary() {
        // add as many as you want
        for ( int i=0; i < 10; i++)
            dictionary.add(new WordSig("key"+i, "value"+i));
    }

    public static class testListDictionary {
        public static void main(String[] args) {
            new ListDictionary();
            // test output
            for ( int i=0; i < dictionary.size(); i++ )
                System.out.println( "<" + dictionary.get(i).getWords() + "|"
                                    + dictionary.get(i).getSignature() + ">");
        }
    }
}
Andreas L.
  • 2,805
  • 23
  • 23