Is it possible to use double-quote characters as part of hashmap key?
I 开发者_JAVA技巧am going to have a string like "hello " world" as a hashmap key. The key is actually from user input, that's why it is possible to have something like that as a key. Is it okay?
Absolutely. The double-quote character is only "special" as far as Java source code is concerned. You can even escape it within Java itself:
HashMap<String, String> map = new HashMap<String, String>();
map.put("foo\"bar", "value");
System.out.println(map.get("foo\"bar")); // Will print value
Here the key itself is foo"bar - the backslash is just for escaping within the string literal.
Yes, of course. Even the 0-Character, which often is used as an End-of-String symbol in C is okey in Java, so there are really no constraints.
Sure. If the key is of type String
, then all characters are allowed. There is no limitation.
Just a reminder: assuming, the user enters:
Jack"o"Lantern
then the Java literal is
"Jack\"o\"Lantern"
As the others told you, strings in java are allowed to contain all unicode characters, so for keys in a hashmap, you're fine.
But be careful when creating SQL queries, http requests or similar using strings which contain unfiltered user input - your software may be open to SQL injection or cross site scripting attacks then. Using mechanisms like prepared statements instead of string concatenation will help in this case.
精彩评论