ArrayList.get() Returning "Incompatible Type"
I'm trying to create a basic class that stores an array of Objects and returns them. I do not have a way of knowing how many objects I will need to store, so I am using an ArrayList instead of a regular Array. However, code that would work with a regular Array does not appear to function with an ArrayList's get() method. Instead, I get an "Incompatible Types" error when I try to return the results of .get().
Even after creating the smallest possible SSCCE, I still am not quite sure why this doesn't function:
Code :
public class EmptyType {
int testInt = 1;
}
Code :
import java.util.*;
public class ArrayListTest {
private ArrayList list;
public ArrayListTest() {
list.add(new EmptyType());
}
public EmptyType GetFirstIndex() {
return list.get(0);
}
}
Re: ArrayList.get() Returning "Incompatible Type"
The code defines an ArrayList without specifying a type - in so doing the get method will return an Object. Specify the type of the ArrayList using Generics (see Lesson: Generics (Updated) (The Java™ Tutorials > Learning the Java Language) ) or cast to the appropriate class before returning the object.
Re: ArrayList.get() Returning "Incompatible Type"
Solved my problem perfectly, thank you. Only glanced at generics up until now, and didn't know they applied to a situation like this. I assumed that the type didn't matter since the compiler had no problems loading the ArrrayList with arbitrary different objects; I thought that I was the one responsible for making sure that I knew what type of object was stored in the list and only performing operations on that type of object.