user3343751
user3343751

Reputation: 5

TreeMap <String,object> ClassCastException

my code:

TreeMap<String,Book> booksTree=new TreeMap<String,Book>(new StringCompare());
Book b1=new Book("b1");
booksTree.put(b1.getCode(), b1);
Book b3=booksTree.get(b1);
System.out.println(b3.toString());

i read in other post here that i have to add comparator so wrote :

import java.util.Comparator;

public class StringCompare implements Comparator<String>
{
    public int compare (String c1, String c2) 
    {
        return c1.compareTo(c2);
    }

}

and i get:

Exception in thread "main" java.lang.ClassCastException: maman18.Book cannot be cast to java.lang.String
at maman18.StringCompare.compare(StringCompare.java:1)
at java.util.TreeMap.getEntryUsingComparator(Unknown Source)
at java.util.TreeMap.getEntry(Unknown Source)
at java.util.TreeMap.get(Unknown Source)
at maman18.Main.main(Main.java:31)

it's the first time i use TreeMap with strings and don't know how to use it very well, please help me fix this so the get function work.

Upvotes: 0

Views: 1370

Answers (3)

Alexis C.
Alexis C.

Reputation: 93842

The problem is that the get method expect a key which has the same data type as you defined your map (i.e String in your case).

So it should be:

Book b3=booksTree.get(b1.getCode());

This is specified in the doc :

ClassCastException - if the key is of an inappropriate type for this map (optional)

It says optional because for an HashMap per example, get will return null. So you would have a NullPointerException on the line System.out.println(b3.toString()); instead.

But in the case of a TreeMap, this exception is thrown.

ClassCastException - if the specified key cannot be compared with the keys currently in the map

Upvotes: 6

Kick
Kick

Reputation: 4923

    Book b3=booksTree.get(b1);  
--------------------------^

The parameter must be String

public V get(Object key) : 

The method call returns the value to which the specified key (String in ur case) is mapped, or null if this map contains no mapping for the key.

Upvotes: 3

Rakesh KR
Rakesh KR

Reputation: 6527

Try with ,

TreeMap<String,Book> booksTree = new TreeMap<String,Book>();

Upvotes: 0

Related Questions