Incompatible types : Object cant not be converted to String in java netbeans

前端 未结 3 705
余生分开走
余生分开走 2021-01-29 15:56

I\'m trying to use object Array in my project and i get an error :

incompatible types: Object cannot be converted to String

on this line :

相关标签:
3条回答
  • 2021-01-29 16:13

    You have two way one is to cast every Object emt1, emt2, .. to String like this :

    ST1 = new String[]{(String)emt1, (String)emt2, (String)emt3, (String)emt4};
    

    Or you should to change the type of your attribute:

    Object emt1, emt2, emt3, emt4;
    

    To String

    String emt1, emt2, emt3, emt4;
    ST1 = new String[]{emt1, emt2, emt3, emt4};
    
    0 讨论(0)
  • 2021-01-29 16:17

    You have declared emt1,emt2,emt3,emt4 as Object. In the last line where you are creating the assigning the array to the variable ST1, you are creating a String array and storing Object intances in it. This is what is causing the problem.

    If you wish to use the objects in this manner and if you are sure that the emt1,emt2,emt3,emt4 objects are all strings, you can add a cast to your code like this:

        ST1 = new String[] { (String) emt1, (String) emt2, (String) emt3, (String) emt4 };
    

    This should work.

    0 讨论(0)
  • 2021-01-29 16:33

    A String is an Object, but an Object is not necessarily a String.

    You try to use variables which are Objects where the compiler expects Strings, and the compiler tells you so. Perhaps the emt1, emt2, emt3 and emt4 variables should have been declared as String? (Hard to tell from the snippet given).

    0 讨论(0)
提交回复
热议问题