有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  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"));
        }
    
  3. # 3 楼答案

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

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