How do I address unchecked cast warnings?

后端 未结 23 1544
醉梦人生
醉梦人生 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:52

    Here's one way I handle this when I override the equals() operation.

    public abstract class Section extends Element> {
        Object attr1;
    
        /**
        * Compare one section object to another.
        *
        * @param obj the object being compared with this section object
        * @return true if this section and the other section are of the same
        * sub-class of section and their component fields are the same, false
        * otherwise
        */       
        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                // this exists, but obj doesn't, so they can't be equal!
                return false;
            }
    
            // prepare to cast...
            Section other;
    
            if (getClass() != obj.getClass()) {
                // looks like we're comparing apples to oranges
                return false;
            } else {
                // it must be safe to make that cast!
                other = (Section) obj;
            }
    
            // and then I compare attributes between this and other
            return this.attr1.equals(other.attr1);
        }
    }
    

    This seems to work in Java 8 (even compiled with -Xlint:unchecked)

提交回复
热议问题