Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

mixing generic & nongeneric

 
Shashank Sharma
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[//Code]
class test034
{
public static void main(String[] args)
{
List <Integer> ll=new ArrayList<Integer>();
ll.add(34);
ll.add(new Integer(65));
System.out.println(ll);
changelist cl=new changelist();
cl.changeit(ll);
}
}
class changelist
{void changeit(List li)
{
li.add(new Integer(57));
li.add(new Integer(87));
System.out.println(li);
}

}
[//Code]

above code compiles without errors but with warnings:"Note: Recompile with -Xlint:unchecked for details. "
According to K&B page 577,if the list is of type Integer and we pass an Integer object to it will compile without warning and any errors.it should give a warning only when we try to push in an object other than Integer.as stated by K & B.please help on this minute detail.
thanks in advance
 
Anit Nair
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear friend,

Whenever you pass a generic collection type to a non generic collection type, as you are doing in the ex. mentioned, there are two scenarios to be taken into consideration.
1)You are just reading the values
2)Are you modifying the collection within the function

1) In this case the code will run without warning
2) In this case regardless of the type of Object you are adding, it will compile with warning. The reason being since you are passing a generic collection type to a non-generic type (ie pre-Java 5) the Java compiler warns that object you are adding may cause problems. This is because there is no way to detect what the type of object is at runtime. Because all the generic information is compile time information.



Hope this helps.
 
camilo lopes
Ranch Hand
Posts: 202
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
checks please:
link
when show this message stand for that you used 1.5 with 1.4. but your code compile and execute normally.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic