-1
public class Main {
    public static void main(String[] args) {
        List[] list = new ArrayList[3];
        list[0] = new ArrayList<Integer>();
        list[0].add("string");
        ArrayList<Integer> arr = new ArrayList<>();
        arr.add("string");
    }
}

Frist question: I already state that the ArrayList should accept Interger. But it do not throw error when I try to assign a "string" into this ArrayList. I really don't know why this happen.

Seconde question: Why I can declare a list by this "List[] list = new ArrayList[3];"

  • 4
    You're not declaring a List, you're declaring an *array* of Lists, which are *raw* Lists that have no generic information and so accept any type. – Bohemian Oct 21 '22 at 02:13
  • 1
    Related: [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) In your case, `List` is a raw list and `List[]` is an array of raw lists. (You _probably_ don't actually want/need an array of lists (raw or otherwise).) – andrewJames Oct 21 '22 at 02:38

1 Answers1

2

The reason is that

List[] list = new ArrayList[3];

By doing it,you make list accept any parameters,in this case list[0] = new ArrayList<Integer>(); works similar to list[0] = new ArrayList<>();

If you want to it just accept Integer,you need to do it as following

List<Integer>[] list = new ArrayList[3];
flyingfox
  • 13,414
  • 3
  • 24
  • 39