简体   繁体   中英

Hashtable content : the first 2 Keys are Null … How to get my saved content

I have a problem with my hashtable... I have a hashtable< String1,String2 > String1 = is a JTextfield as my Hashtable Key String2 = is a JTextArea as my Hashtable content myHashtable.put(JTextfield.getText(),JTextArea.getText()); and now I want to write all my saved content from my Hashtable into a file but my first 2 contents are "null"

for (int i = 0; i < myHashtable.size(); i++) {
            String[] key = myHashtable.keySet().toString().split(", ");
            writer.println(key[i].replace("]", "").replace("[", "") + ": "
                    + myHashtable.get(key[i]));

the following output should looks like:

examplekey : some content
examplekey2 : more content
examplekey3 : some content
but it looks like:

examplekey : null
examplekey2 : null
examplekey3 : some content

the reason why I write it so, is that I want to read this file, to get my Hashtable content after a restart and the .keySet function gives me a "[" and "]" at the start and end thats why I replace this with "".

You should run your program through a debugger to better understand what it is doing.

Let's follow an example:

Hashtable<String, String> myHashtable = new Hashtable<>();
myHashtable.put("1", "rat");
myHashtable.put("2", "cat");
myHashtable.put("3", "bat");

Running your loop, the first iteration will go like this:

myHashtable.keySet().toString() -> "[3, 2, 1]"

String[] key = myHashtable.keySet().toString().split(", ") -> "[3", "2", "1]"

key[0] -> "[3"
key[0].replace("]", "").replace("[", "") -> "3"
myHashtable.get(key[0]) -> myHashtable.get("[3") -> null

As you can see, replace() returns a new string with the replacement in place of the target. It does not modify the original string. So when you call myHashtable.get(key[0]) the key is "[3" , which is not in the hashtable, so it returns null . If you run your code with the example hashtable you will get something like this in your file:

3: null
2: cat
1: null

It works for the keys in the middle, "2" in the example, because when you split the string they already don't have a "[" or "]" attached to them.

Now, notice that when you do myHashtable.keySet().toString().split(", ") you already have access to the elements in the keyset. You don't have to convert it to a string and then try to get the keys from this string. So you can do:

for (String key : myHashtable.keySet()) {
    writer.println(key + ": " + myHashtable.get(key));
}

We can make it a bit faster if we iterate over all entries directly:

for (Map.Entry<String, String> entry : myHashtable.entrySet()) {
    writer.out.println(entry.getKey() + ": " + entry.getValue());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM