-1

I want to know what kinds of reference can be array elements.

I know that there're primitive types like:

String[] strs = new String[5];

But there is no

List<String>[] stringList; 

However, when I new a class, there is

Class Student{
     String name;
     List<String> courses;
}

Student[] students = new Student[5];

It says "The element type of an array may be any type, whether primitive or reference."

I think Student is reference and List<> is also reference. What's the difference between them?

Thanks.

travis
  • 17
  • 1
  • 3
  • "But there is no `List[] stringList;`" There is, if you declare and create it. – laune Jan 05 '18 at 20:11
  • There is no difference. Simple type arrays is one kind; arrays of Object is another kind. That's all there is to it. – laune Jan 05 '18 at 20:12
  • Also note that `String` is not a primitive type. See https://docs.oracle.com/javase/specs/jls/se9/html/jls-4.html#jls-4.2 – Jon Skeet Jan 05 '18 at 20:18

1 Answers1

1

Anything can go in an array. Primitives, other arrays, or lists.

Any of the following are legitimate declarations:

int[] intArray;
int[][] arrayOfIntArrays;
List <String> stringList;
List <String[]> stringArrayList; 
List <List<String[]>> badIdea; //list of a list of string arrays
List<String>[] array of a list of strings

etc.

An array is a subclass of Object. There is nothing special about it except that java gave it some unique syntax. Otherwise, it's just like anything else you run into in java.

JoshuaD
  • 2,694
  • 3
  • 26
  • 49
  • But when I use " List l = new List<>()[5] " There's an error. How can I create a new array of a list of strings – travis Jan 08 '18 at 14:39
  • List stringArrayList = new ArrayList <> (); for (int i = 0; i < stringArrayList.size(); i++ ) { stringArrayList.add (new String[ 10 ]; ) } – JoshuaD Jan 08 '18 at 17:11
  • How can I create an array of a list of strings like your last code "List[] " ? – travis Jan 08 '18 at 20:12
  • List[] listOfArrays = new List[5]; should work. – JoshuaD Jan 08 '18 at 20:26
  • Also -- making an array of lists or a list of arrays probably means you're doing something wrong. I'm helping with the syntax, but you should really consider what you're doing and whether it makes the most sense. :) – JoshuaD Jan 08 '18 at 20:27