jake2389
jake2389

Reputation: 1174

array required, but java.lang.String found Java Class Array Error

I'm getting the following error:

array required, but java.lang.String found

and I'm not sure why.

What I'm trying to do is put an instance of an object (I believe that is correct terminology), into an array of that type of class (of the object).

I have the class:

public class Player{
     public Player(int i){
           //somecodehere
     }
}

then in my main method I create an instance of it:

static final Player[] a = new Player[5]; // this is where I'm trying to create the array.
public static void main(String[] args){
     Player p = new Player(1);
     a[0] = p; //this is the line that throws the error
}

Any ideas why this is?

Upvotes: 1

Views: 2567

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279880

In your code, the only way I see for that error to happen is if you actually had

static final Player[] a = new Player[5]; // this is where I'm trying to create the array.
public static void main(String[] args){
    String a = "...";
    Player p = new Player(1);
    a[0] = p; //this is the line that throws the error
}

In this case, your local variable a would shadow the static variable of the same name. The array access expression

a[0]

would therefore cause a compilation error like

Foo.java:13: error: array required, but String found
                a[0] = p; // this is the line that throws the error

since a is not an array, but the [] notation only works for array types.

You probably just need to save and recompile.

Upvotes: 5

Related Questions