What does “The type ArrayList is not generic” mean?

前端 未结 3 1879
猫巷女王i
猫巷女王i 2020-12-06 19:36

I am new to Java and trying to learn the various collections that programmers can use. I imported \"java.util\" into a scrapbook in Eclipse and inspected the following code.

3条回答
  •  被撕碎了的回忆
    2020-12-06 19:52

    Yes the problem goes away for 1.5 and above. It feels like the question is not completely addressed though, I'm adding my 2 cents in case anybody comes across this question. It's mainly about this part of the question:

    I did not make a generic array list; I made an array list of strings.

    The error message mentioned:

    > The type ArrayList is not generic; it cannot be parameterized with arguments

    > Syntax error, parameterized types are only available if source level is 5.0

    What it actually means is, since Java 1.5 we can use Type parameters also (where in one was used to using value parameters). JDK 1.5 introduces generics, which allows us to abstract over types (or parameterized types).

    The class designers can be generic about types in the definition. The arrayList implementation would be as below:

    public class ArrayList implements List .... {
        // Constructor
        public ArrayList() {...}
    
        // Public methods
        public boolean add(E e) {...}
        public void add(int index, E element) {...}
        public boolean addAll(int index, Collection c) {...}
        public abstract E get(int index) {...}
        public E remove(int index) {...}
        ...
    }
    

    Where E can be any type like String or Integer etc. Hence the name generic arrayList.

    The users can be specific in the types during the object instantiation or method invocation which was done in this example like below:

    ArrayList list = new ArrayList();
    

    (Which was the confusion in above case, if I am not wrong :-))

    Example of the usage of generics (if needed):

    // Declaring a DAO layer
    public interface IMasterAbstractDao {
        public E findById(I id) {...}
        public void delete(E e) {...}
        public List findByCriteria(Criterion criterion) {...}
    }
    

    Where E is the entity type returned. This can be used for all the Model beans defined in the system making it generic.

    Hope this helps.

    Reference: Java Programming Tutorial - Generics

提交回复
热议问题