错误:找不到合适的put方法(String,int)

时间:2014-02-27 20:18:21

标签: java methods map long-integer autoboxing

编译时出错:

TreeMap <String, Long> myMap = new TreeMap <String, Long>();
//populate the map
myMap.put("preload_buffer_size", 1024);
myMap.put("net_buffer_length", 1024);
//etc...


error: no suitable method found for put(String,int)
    myMap.put("preload_buffer_size", 1024);
         ^
method TreeMap.put(String,Long) is not applicable
  (actual argument int cannot be converted to Long by method invocation conversion)
method AbstractMap.put(String,Long) is not applicable
  (actual argument int cannot be converted to Long by method invocation conversion)

我需要使用Long,而不是int 我真的不知道如何解决它,如果你能帮助我,我将不胜感激。

3 个答案:

答案 0 :(得分:1)

myMap.put("preload_buffer_size", 1024L);

答案 1 :(得分:1)

您正在尝试将具有Integer值的String键(以其原始形式int)放入您指定为String to Long映射的映射中。所以它只接受

myMap.put(String, Long);

通过在数字中添加“L”,编译器会将其识别为Long而不是默认的Integer。

以便为什么以下是解决方案:

myMap.put("preload_buffer_size", 1024L);

答案 2 :(得分:1)

问题是,您尝试将数字文字放在以String为键,Long作为值的地图中。默认情况下,java中的数字文字是int,所以要么写:

 TreeMap <String, Long> myMap = new TreeMap <String, Long>();
 //populate the map
 myMap.put("preload_buffer_size", 1024L);
 myMap.put("net_buffer_length", 1024L);

TreeMap <String, Long> myMap = new TreeMap <String, Long>();
//populate the map
myMap.put("preload_buffer_size", new Long(1024));
myMap.put("net_buffer_length", new Long(1024));