[英]Java : Map showing error : bad operand type for binary operator “+”
以下是我的代碼。 我在Map中成功添加了值,但是當嘗試獲取特定鍵的值並更新它時,沒有值得到
獲取錯誤:二元運算符“+”的錯誤操作數類型
Map map = new HashMap();
System.out.println("Enter the number :");
int k=sc.nextInt();
System.out.println(map.get(k));
System.out.println("Enter the value:");
int v=sc.nextInt();
map.put(k, map.get(k)+v); //getting error here: bad operand type for binary operator "+"
你沒有使用泛型(你正在使用原始類型 ),所以編譯器不知道map中有什么類型的值 - 就編譯器而言, map.get(k)
返回Object
,並且有no +(Object, int)
運算符。
只需在map
聲明和初始化中使用泛型:
// Java 7 and later, using the "diamond operator"
Map<Integer, Integer> map = new HashMap<>();
要么:
// Java 5 and 6 (will work with 7 and later too, but is longer)
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
其余的將編譯沒有問題。
如果您不熟悉泛型,請參閱教程和綜合常見問題解答 。 你應該非常非常少地使用原始類型(幾乎從不)。 您應該能夠配置IDE或編譯器,以便在執行此操作時向您發出警告(例如,使用-Xlint
for javac
)。
您的map
是原始HashMap
。 因此,值可以是任何類型。 您不能將+
運算符與java中的任何類型的對象一起使用。
要解決此問題,請定義如下的通用映射
Map<Integer, Integer> map = new HashMap<>(); //Java 7 version
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); //Java 5 and later versions
這里,key和value都是Integer的類型,因此你可以使用+
運算符
您的地圖不使用泛型。
做這個
Map<Integer, Integer> map = new HashMap<>();
(假設你有Java 7+) Map<Integer, Integer> map = new HashMap<Integer, Integer>();
(假設你有Java 5+)
當不使用泛型時, map.get()
的結果是Object
,當然不能與+
運算符一起使用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.