How do I address unchecked cast warnings?

后端 未结 23 1731
醉梦人生
醉梦人生 2020-11-22 03:06

Eclipse is giving me a warning of the following form:

Type safety: Unchecked cast from Object to HashMap

This is from a call to

23条回答
  •  时光说笑
    2020-11-22 03:45

    The Objects.Unchecked utility function in the answer above by Esko Luontola is a great way to avoid program clutter.

    If you don't want the SuppressWarnings on an entire method, Java forces you to put it on a local. If you need a cast on a member it can lead to code like this:

    @SuppressWarnings("unchecked")
    Vector watchedSymbolsClone = (Vector) watchedSymbols.clone();
    this.watchedSymbols = watchedSymbolsClone;
    

    Using the utility is much cleaner, and it's still obvious what you are doing:

    this.watchedSymbols = Objects.uncheckedCast(watchedSymbols.clone());
    

    NOTE: I feel its important to add that sometimes the warning really means you are doing something wrong like :

    ArrayList intList = new ArrayList();
    intList.add(1);
    Object intListObject = intList; 
    
     // this line gives an unchecked warning - but no runtime error
    ArrayList stringList  = (ArrayList) intListObject;
    System.out.println(stringList.get(0)); // cast exception will be given here
    

    What the compiler is telling you is that this cast will NOT be checked at runtime, so no runtime error will be raised until you try to access the data in the generic container.

提交回复
热议问题