File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Incompatible types Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Incompatible types" Watch "Incompatible types" New topic

Incompatible types

Karu Raj
Ranch Hand

Joined: Aug 31, 2005
Posts: 481
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(;
11 System.out.print(iw);
12 }
13 }
Gyan Shankar
Ranch Hand

Joined: Dec 12, 2005
Posts: 65
Better check out the api for TreeMap
It returns Object so you need a cast

SCJP(1.4), SCWCD(1.4), SCBCD(1.3), SCDJWS
Poonam Thawani

Joined: Oct 11, 2005
Posts: 13
Compilation error occurs due to tm.get(; This statement returns Object.
Integer iw = tm.get(;-- 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(; instead of 10th statement.
Karu Raj
Ranch Hand

Joined: Aug 31, 2005
Posts: 481
Thanks for the explanation


do we expect such in SCJP exam in Collections.

santosh kothapalli

Joined: Dec 27, 2005
Posts: 26
what you should remember is collections when iterated give objects.
So they should be type casted.
Same happens even with enumeration.


Santosh K<br />SCJP 1.4,SCWCD
I agree. Here's the link:
subject: Incompatible types
It's not a secret anymore!