如何将HashMap用作LinkedHashSet

时间:2017-04-18 06:07:30

标签: java hashmap linkedhashset

当我运行此程序时: -

import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;

public class try1 {

    public static void main(String args[]) {

        Map<String, Object> props = new HashMap<String, Object>();
        props.putIfAbsent("videos", new LinkedHashSet<String>());
        System.out.println(LinkedHashSet<String>(props.get("videos")).add("video_url");

    }
}

我得到3个错误: -

try1.java:14: error: cannot find symbol
        System.out.println(LinkedHashSet<String>(props.get("videos")).add("yoyo"));//.add("video_url");
                           ^
  symbol:   variable LinkedHashSet
  location: class try1
try1.java:14: error: cannot find symbol
        System.out.println(LinkedHashSet<String>(props.get("videos")).add("yoyo"));//.add("video_url");
                                         ^
  symbol:   variable String
  location: class try1
try1.java:14: error: cannot find symbol
        System.out.println(LinkedHashSet<String>(props.get("videos")).add("yoyo"));//.add("video_url");
                                                                     ^
      symbol:   method add(String)
      location: class Object
    3 errors

我正在尝试将HashMap值用作LinkedHashSet,但是会出现这些错误。我该怎么办?

3 个答案:

答案 0 :(得分:1)

你的语法有错误,首先你需要将对象转换为LinkedHashSet然后添加一个字符串

   System.out.println( ((LinkedHashSet<String>)(props.get("videos")) ).add("video_url") );

答案 1 :(得分:1)

我想你想使用java.util.LinkedList作为Map的值。

Map<String, List<String>> props = new HashMap<>();
props.putIfAbsent("videos", new LinkedList<String>());
props.get("videos").add("video_url");
System.out.println(props);

但是如果你想使用一个迭代作为put order的相同顺序的地图。

Map<String, String> props = new LinkedHashMap<>();
props.putIfAbsent("videos", "video_url");
System.out.println(props);

答案 2 :(得分:-2)

正确的代码如下:

public static void main(String[] args) {
        Map<String, Object> props = new HashMap<String, Object>();
        props.putIfAbsent("videos", new LinkedHashSet<String>());
        System.out.println(((LinkedHashSet)(props.get("videos"))).add("video_url"));
    }