Click here to Skip to main content
15,936,014 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
for java 5.0 and greater.

ArrayList<test> myList = new ArrayList<test>();
test t1 = new test();
myList.add(t1); no error b'se can only put "test" type object
myList.add(new Integer(23));

But if we remove "<test>" from left side

ArrayList myList = new ArrayList<test>(); and now

myList.add(new Integer(23)); no error

But for

ArrayList<test> myList = new ArrayList();

myList.add(new Integer(23)); gives error

Can anyone explain me what i am missing here.

What I have tried:

import java.util.*;

public class Main {

public static void main(String[] args) throws Exception {

ArrayList l = new ArrayList<test>();
l.add(new Integer(3));


class test{
int i;
void m1(){
System.out.println("inside m1 method");

Updated 19-Jan-21 2:53am

1 solution

You are missing many programming concepts, there.
A starting point: Why Use Generics? (The Java™ Tutorials > Learning the Java Language > Generics (Updated))[^]
Share this answer
Mohit Mandloi 19-Jan-21 9:54am    
understood that ArrayList<test> takes input as "test" type object and return "test" object but i don't understood meaning(or say use) of "<test>" in the following line.

new ArrayList<test>()
CPallini 19-Jan-21 10:00am    
Creates a collection (an ArrayList) of test objects
Mohit Mandloi 19-Jan-21 10:17am    
If it's creating arraylist of test objects than why it is allowing different type of object to be assigned in arraylist

ArrayList myList = new ArrayList<test>();

myList.add(new Integer(23)); no error
CPallini 19-Jan-21 10:40am    
Because you are assigning it to a non-generic ArrayList.
"This is the consequence of a somewhat unfortunate limitation of generic types in Java." From

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900