简体   繁体   English

使用泛型实例化Java数组

[英]instantiating java array using generics

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. 我要做的就是创建一个ArrayLinearList<String>且大小为2的实例,并将一些字符串放入其中。 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> 错误消息是: 错误:不兼容的类型:字符串不能转换为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. 我在Java中使用泛型时在语法上遇到了很多麻烦。 In my mind I have an array of size 2 where I am going to be placing strings. 在我看来,我有一个大小为2的数组,将在其中放置字符串。 I will add more methods later but I want to understand why my current syntax is incorrect for placing this string in the array. 稍后我将添加更多方法,但我想了解为什么我当前的语法对于将此字符串放置在数组中是不正确的。

Here: 这里:

   ArrayLinearList<String>[] myList;

you define an array that holds ArrayLinearList<String> elements, not Strings, this is why you get the error message. 您定义一个包含ArrayLinearList<String>元素而不是ArrayLinearList<String>的数组,这就是为什么您收到错误消息的原因。

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). 这里ArrayLinearList<String>表示您的列表将保存String类型的值(前提是我们在代码中正确定义了它)。 But ArrayLinearList<String>[] will hold only reference of type ArrayLinearList and not String itself. 但是ArrayLinearList<String>[]将仅保存ArrayLinearList类型的引用,而不保存String本身。

You need to use 您需要使用

myList.array[0] = "one";

Because myList is not an array. 因为myList不是数组。 It's an object which you use to store an array within. 这是一个用于在其中存储数组的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM