Type mismatch error between java.lang.String and String

13,113

Solution 1

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 {

Solution 2

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.

Share:
13,113
StumpedCoder
Author by

StumpedCoder

I am a high school student who enjoys coding and who plans to pursue Computer Science in college and hopefully into my career. I taught myself programming by watching online tutorials and by hunting down answers to difficult questions with the power of Google. However, occasionally I'll come across a problem for which I cannot find a solution anywhere. For that, I turn to the amazing StackOverFlow community.

Updated on June 25, 2022

Comments

  • StumpedCoder
    StumpedCoder almost 2 years

    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.