Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics: incompatible type required String; found: java.lang.String

Tags:

java

generics

I'm getting this compiler error in netbeans:

incompatible types required: String found: java.lang.String

I'm kind of lost as why this happens?

Code:

private class StringIterator<String> implements Iterator<String> {

    private Iterator<Entry<K, byte[]>> i = internalMap.entrySet().iterator();

    @Override
    public boolean hasNext() {
        return i.hasNext();
    }

    @Override
    public String next() {
        return decompress(i.next().getValue());// error on this line
    }

    @Override
    public void remove() {
        i.remove();
    }
}
like image 233
beginner_ Avatar asked Dec 09 '11 10:12

beginner_


4 Answers

You should remove the type argument from the StringIterator class. This is causing the compiler to consider any occurrence of String in the class to be a generic type rather than java.lang.String.

private class StringIterator implements Iterator<String> {
like image 155
gkamal Avatar answered Oct 21 '22 17:10

gkamal


What is decompress? If it is a method, then it must also return String.

like image 33
Its not blank Avatar answered Oct 21 '22 16:10

Its not blank


What are your imports? Did you maybe import the "wrong" String? Plus, what is decompress?

Update: see other reply, which has the correct answer. You named your generic "String". Remove the generic you don't use.

like image 1
Has QUIT--Anony-Mousse Avatar answered Oct 21 '22 16:10

Has QUIT--Anony-Mousse


I wanted to supply another situation where this can occur as it was stumping me for a while. The solution gkamal stated is correct.

In my case, I had the following:

public class NodeLabelTransformer<V, String> implements Transformer<V, String>
{
....
}

but I was receiving the error.

@Override
public String transform(V s)
{
   StringBuilder label;
   label = new StringBuilder();
   label.append("MyLabelText");
   return (label.toString());
}

In this case the solution is that my class should be declared as:

public class NodeLabelTransformer<V> implements Transformer<V, String>
{

I just wanted to point out, that the parameters of the Transformer interface are still the same, but my class declaration differs.

like image 1
mwjohnson Avatar answered Oct 21 '22 17:10

mwjohnson