Trying to convert ArrayList to Array, but IDE & ldquo; can not find the symbol & rdquo;

advertisements

I have this ArrayList of Animal objects:

ArrayList<Animal> animals = new ArrayList<Animal>();
animals.add(new Animal(1, "animal1", 50, "10 Janvier 2016", "Noir", 4, true));
animals.add(new Animal(2, "animal2", 40, "10 Janvier 2016", "Noir", 4, true));

I'm trying to create a method of conversion of this ArrayList into an Array. So far i've come up with :

public Animal[] tArray(){
    return animals.toArray();
}

But my IDE says he can't find the symbol variable animals.

How could i transform my ArrayList animals into an array ?

Edit : i think my problem isn't related to the method itself but more the structure of the code into my class.


You are trying to convert a local variable to an array inside an instance method. This is not going to work, because local variables are, well, local to methods or constructors in which they are declared.

You need to do one of the following:

  • Declare a field private List<Animal> animals = new ArrayList<Animal>(); and remove animals local variable, or
  • Declare an array field private Animal[] animalArray, and assign it right after making the animals local; getter would then return aninalsArray.