简体   繁体   English

是否可以使用双引号字符作为hashmap键的一部分?

[英]Is it possible to use double-quote characters as part of hashmap key?

我将有一个像“hello”world这样的字符串作为一个hashmap键。这个键实际上是来自用户输入,这就是为什么有可能把这样的东西作为一个键。这样可以吗?

Absolutely. 绝对。 The double-quote character is only "special" as far as Java source code is concerned. 就Java源代码而言,双引号字符只是“特殊”。 You can even escape it within Java itself: 你甚至可以在Java本身内逃避它:

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. 这里的关键本身就是foo“bar - 反斜杠只是用于在字符串文字中转义。

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. 甚至0字符(通常在C中用作字符串结尾符号)在Java中也是如此,因此实际上没有约束。

Sure. 当然。 If the key is of type String , then all characters are allowed. 如果键的类型为String ,则允许所有字符。 There is no limitation. 没有限制。

Just a reminder: assuming, the user enters: 只是提醒一下:假设,用户输入:

 Jack"o"Lantern

then the Java literal is 那么Java文字是

 "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. 正如其他人告诉你的那样,java中的字符串允许包含所有unicode字符,因此对于hashmap中的键,你没问题。

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. 但是在使用包含未经过滤的用户输入的字符串创建SQL查询,http请求或类似信息时要小心 - 您的软件可能会对SQL注入或跨站点脚本攻击开放。 Using mechanisms like prepared statements instead of string concatenation will help in this case. 在这种情况下,使用预处理语句等机制而不是字符串连接将有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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