Why this code gets a warning?

Write here if you have problems with your Java source code

Moderator: Board moderators

Post Reply
ImLazy
Experienced poster
Posts: 215
Joined: Sat Jul 10, 2004 4:31 pm
Location: Shanghai, China

Why this code gets a warning?

Post by ImLazy »

Code: Select all

import java.util.*;
public class Base {
    private TreeSet set;
    public Base() {
        set = new TreeSet<String>();
        try {
            set.add("abc");
        } catch (Exception e) {}
    }
}
I compiled it by jdk1.5.0_06.
I stay home. Don't call me out.
Darko
Guru
Posts: 580
Joined: Fri Nov 11, 2005 9:34 am
Location: Calgary, Canada

Post by Darko »

Well, you use a general set to store a set of Strings - declare it as

Code: Select all

private TreeSet<String> set;
and it should be OK

Btw, what are you catching there? I don't think add() throws anything.
ImLazy
Experienced poster
Posts: 215
Joined: Sat Jul 10, 2004 4:31 pm
Location: Shanghai, China

Post by ImLazy »

Thank you.

BTW, the add() method thorws "ClassCastException". Of course we usually need not to catch it. But because I get warning, I just want to tell the compiler I do everything safely. Now I have deleted the "try" and "catch".
I stay home. Don't call me out.
Post Reply

Return to “Java”