Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type mismatch error between java.lang.String and String

This is really an odd problem, I've never encountered something like it. The following is a helper class I have declared inside a larger class. It runs perfectly fine as is:

private static class Tree<String> {
    private Node<String> root;

    public Tree(String rootData) {
        root = new Node<String>();
        root.data = rootData;
        root.children = new ArrayList<Node<String>>();
    }

    private static class Node<String> {
        String data;
        Node<String> parent;
        ArrayList<Node<String>> children;
    }
}

However, by messing around I discovered a confounding problem. By replacing this line:

root.data = rootData;

with:

root.data = "some string literal";

I get this error:

Type mismatch: cannot convert from java.lang.String to String

I tested out some string literal assignments in other classes and it appears to work perfectly fine. I recently updated to Java 1.7.0_15 and recently downloaded and installed Eclipse 4.2. I suspect there might be some confusion in the build path or something. Using Ubuntu 12.04

Any help would be greatly appreciated! I've searched and searched and couldn't find anything close to this problem.

like image 998
StumpedCoder Avatar asked Mar 24 '13 06:03

StumpedCoder


2 Answers

You're creating a new generic type parameter named "String", which is probably not what you want.

Change

private static class Tree<String> {

to

private static class Tree {
like image 169
j__m Avatar answered Oct 08 '22 21:10

j__m


It seems like you are trying to create a generic class using "String" as the name of your generic type. What generic types do is whenever you create an object from the class, it replaces whatever is in the <> with the new type.

So in your class, if you created a Tree<Integer>, ever instance of "String" in your class would be replaced by "Integer". This is the way some classes such as ArrayList work to allow any type to be used.

Usually when using generic types, a single letter, such as "T", is used to avoid it being the same as a real class type.

So in your case, you are trying to set a "String" that is not actually a String as an actual string.

like image 28
Jsdodgers Avatar answered Oct 08 '22 22:10

Jsdodgers