Converting non-generic List type to Generic List type in Java 1.5

后端 未结 5 2121
鱼传尺愫
鱼传尺愫 2021-02-07 06:21

I have a List that is guaranteed to contain just one type object. This is created by some underlying code in a library that I cannot update. I want to create a List
5条回答
  •  名媛妹妹
    2021-02-07 07:07

    If you just cast to List in any old place you will get an "unchecked" compiler warning. We resolved that by moving it to a utility method.

    public class Lists {
        @SuppressWarnings({"unchecked"})
        public static  List cast(List list) {
            return (List) list;
        }
    }
    

    Caller now gets no warning, e.g.:

    for (Element child : Lists.cast(parent.getChildren())) {
        // ...
    }
    

    That checkedList utility is in theory a great idea, but in practice it sucks to have to pass in the class you expect. I hope Java will get runtime generic typing information eventually.

提交回复
热议问题