Reputation: 1775
I am creating a list data structure and am having trouble with the generics syntax for actually using it. All I am trying to do is create an instance of ArrayLinearList<String>
and of size 2 and put some strings in it. I have been trying to figure out why setting the first slot to "one" is not correct. This is the error and my code snippet.
myList[0] = "one";
The error message is: error: incompatible types: String cannot be converted to ArrayLinearList<String>
public class ArrayLinearList<E> implements LinearListADT<E> {
private Object[] array;
int currentSize = 0;
//Constructor (no arguments)
public ArrayLinearList() {
currentSize = 2;
// array = (ArrayLinearList[]) new Object[2]; //Start with a container of size 2
array = new Object[2];
}
public static void main(String[] var0) {
ArrayLinearList<String>[] myList;
myList = new ArrayLinearList[2];
myList[0] = "one";
}
}
I am having quite a bit of trouble with the syntax with using generics in java. In my mind I have an array of size 2 where I am going to be placing strings. I will add more methods later but I want to understand why my current syntax is incorrect for placing this string in the array.
Upvotes: 0
Views: 110
Reputation: 869
You need to use
myList.array[0] = "one";
Because myList
is not an array. It's an object which you use to store an array within.
Upvotes: 0
Reputation: 37083
Your code here
ArrayLinearList<String>[] myList;
myList = new ArrayLinearList[2];//you have defining array myList of type ArrayLinearList
myList[0] = "one";//you are trying to store String to array which can hold ArrayLinearList
Here ArrayLinearList<String>
means that your list will hold values of type String (provided we define it correctly in the code). But ArrayLinearList<String>[]
will hold only reference of type ArrayLinearList and not String itself.
Upvotes: 1
Reputation: 333
Here:
ArrayLinearList<String>[] myList;
you define an array that holds ArrayLinearList<String>
elements, not Strings, this is why you get the error message.
Upvotes: 1