This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Incompatible types" Watch "Incompatible types" New topic
Author

Incompatible types

Karu Raj
Ranch Hand

Joined: Aug 31, 2005
Posts: 479
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

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
Greenhorn

Joined: Oct 11, 2005
Posts: 13
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

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

welldone

do we expect such in SCJP exam in Collections.

santosh kothapalli
Greenhorn

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

cheers,
Santu.


Santosh K<br />SCJP 1.4,SCWCD
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Incompatible types
 
Similar Threads
Type safety: Unchecked cast from Object to TreeMap<String,String>
J2SE Questions
TreeMap
Collections
Regarding sorting of TreeMap