The List listofinteger
is of type Integer
, but accepting String Object and when i do check for instance of Integer
, it is giving true , its too strange , can anybody explain what is happening.
All i know is when i send the List listofinteger
to method ,it is given reference to List reference variable of no type , when i add it takes the input as String , now when i return the List listofanything
to List of Integer type
, it should take because its a reference .
Now but i check for instanceof
, it is printing true
for Integer
, but its String
.
import java.util.ArrayList;
import java.util.List;
public class TestEx {
List<Integer> listofinteger=new ArrayList<Integer>(); //list of integer type
public static void main(String... args)
{
TestEx f=new TestEx();
f.listofinteger.add(123); //adds integer by wrapping it(auto)
f.listofinteger=f.addelement(f.listofinteger);
if(f.listofinteger.get(1) instanceof Integer);
{
System.out.println("true"); //prints true here
System.out.println(f.listofinteger.get(1));
}
}
List<Integer> addelement(List listofanything)
{
listofanything.add("asdasdasd"); //adding String object
return listofanything;
}
}
I know that the method addelement(List listofanything )
here should be given a type Integer but i am here testing it , to understand the concept of Generics