Page 1 of 1

Why this code gets a warning?

Posted: Tue Apr 25, 2006 12:43 am
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.

Posted: Tue Apr 25, 2006 1:15 am
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.

Posted: Tue Apr 25, 2006 2:40 am
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".