Java不安全操作

3

当编译一小段Java代码时,我收到了一个编译注意事项,表示存在不安全的操作。我希望知道如何改变我的数据结构使其更加安全。

概念:我需要根据字符串的长度将输入的字符串组织成桶,这个长度可以是任意的(但小于80个字符)。

代码:

Map<Integer, List> buckets = new HashMap<Integer, List>();
            if(!buckets.containsKey(length))
            {
                buckets.put(length,new Vector<wordValues>());
            }
            //Now add the temp to the bucket
            buckets.get(length).add(new wordValues(temp));

然后我将字符串添加到相应大小的列表中。

有更好的方法吗?


请参考此答案:https://dev59.com/unI-5IYBdhLWcg3wkJIA - Steve Atkinson
为什么要同时使用 containsKeyget - obataku
2个回答

10
您混合了未使用泛型的List与泛型List,尝试使用以下代码:
Map<Integer, List<wordValues>> buckets = new HashMap<Integer, List<wordValues>>();

通常类名以大写字母开头,例如WordValues


3
问题在于你正在使用原始类型List,而不是参数化泛型类型List<WordValues>。 Oracle的Java教程中详细讲解了泛型。
Map<Integer, List<WordValues>> buckets = new HashMap<>();
...
List<WordValues> values = buckets.get(length);
if (values == null) {
  values = buckets.put(length, new ArrayList<WordValues>());
}
values.add(new WordValues(temp));

一些小贴士:
  • containsKey and get both do identical look-ups. It seems kinda odd to do the it twice :-p
  • Avoid using Vector in favor of ArrayList. If you need it to be synchronized, consider decorating it via Collections.synchronizedList.

    Collections.synchronizedList(new ArrayList<WordValues>())
    
  • Java 7 supports type parameter inference which can significantly ease the burden on you. Notice above I didn't have to type HashMap<Integer, List<WordValues>>; instead, I merely typed HashMap<>, taking advantage of the new diamond operator.
  • Avoid using class names that begin with a lower-case character; this is generally hard to read (and against the Oracle Code Conventions). Consider naming your class WordValues rather than wordValues.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接