Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Incompatible types

 
Karu Raj
Ranch Hand
Posts: 481
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I compiled the code I got Incompatible types at line 10

Do explian me clearly and fully

do we get such questions in exam Bert???

import java.util.*;
2 public class Pippin {
3 public static void main(String argv[]){
4 TreeMap tm = new TreeMap();
5 tm.put("one", new Integer(1));
6 tm.put("two",new Integer(3));
7 tm.put("three",new Integer(2));
8 Iterator it = tm.keySet().iterator();
9 while(it.hasNext()){
10 Integer iw = tm.get(it.next());
11 System.out.print(iw);
12 }
13 }
14.}
 
Gyan Shankar
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Better check out the api for TreeMap
It returns Object so you need a cast
 
Poonam Thawani
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Compilation error occurs due to tm.get(it.next()); This statement returns Object.
Integer iw = tm.get(it.next());-- In this statement iw is object of class Integer.
As you are trying to assign instance of class Object to Integer this error occurs.
As Integer is subclass and Object is base class you cannot assign subclass instance to instance of base class Object.
So before assigning just cast it to type Integer and the problem is solved.

Use Integer iw = (Integer)tm.get(it.next()); instead of 10th statement.
 
Karu Raj
Ranch Hand
Posts: 481
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the explanation

welldone

do we expect such in SCJP exam in Collections.

 
santosh kothapalli
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Karthik,
what you should remember is collections when iterated give objects.
So they should be type casted.
Same happens even with enumeration.

cheers,
Santu.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic