简体   繁体   English

编译错误“不兼容的类型”

[英]Compile error “incompatible types”

I have compile error: 我有编译错误:

Error: incompatible types: Object cannot be converted to String.

at line String buf = it.next(); String buf = it.next();

public String getMostFrequentColor() {
    HashMap<String, Integer> colors = countColors();
    int count = 0;
    String mfcolour;
    Iterator it = colors.keySet().iterator();
    while (it.hasNext()) {
        String buf = it.next();
        if (colors.get(buf) > count) {
            count = colors.get(buf);
            mfcolour = buf;
        }
    }

    return mfcolour;
}

I don't have any Idea why this could happen. 我不知道为什么会发生这种情况。 it.next() should return a String in my opinion. 我认为it.next()应该返回一个String。

使用Iterator<String>代替Iterator

Iterator<String> it = colors.keySet().iterator();

You are using an Iterator without a generic argument. 您正在使用没有通用参数的Iterator This means that it will return Object types. 这意味着它将返回Object类型。 Either amend its declaration (by turning Iterator it into Iterator<String> it ) or manually cast the object retrieved by it.next() . 要么修改其声明(通过将Iterator it变为Iterator<String> it ),要么手动转换由Iterator it检索的对象it.next()
The latter may be subject to type-safety issues though! 后者可能会遇到类型安全问题!

The return type of the next() method in the Iterator class is Object . Iterator类中next()方法的返回类型为Object Since you know that your HashMap has a key set of type String , you'll need to cast the result of it.next() to String : 由于您知道HashMap的键集类型为String ,因此需要将它的结果it.next()String

String buf = (String) it.next();

Try casting String to prevent this problem at compile time. 尝试强制转换String以防止在编译时出现此问题。 The compiler gives you this warning simply because Java is a strict-typed language. 仅仅因为Java是一种严格类型的语言,编译器才会向您发出此警告。 At runtime, if the variable cannot be cast, you will only run into problems then. 在运行时,如果无法强制转换变量,则只会遇到问题。

String buf = (String) it.next();

Or you could make it more specific by specifying the type of Iterator you want to use. 或者,您可以通过指定要使用的Iterator的类型来使其更加具体。 This is probably the better option. 这可能是更好的选择。

Iterator<String> it = colors.keySet().iterator();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM