tag:blogger.com,1999:blog-5689812823462613341.post4509879066249445065..comments2022-03-26T10:40:25.681-07:00Comments on Glen on Programming: Checking an Unchecked Cast in Java 5 or LaterAnonymoushttp://www.blogger.com/profile/01199522537419481981noreply@blogger.comBlogger1125tag:blogger.com,1999:blog-5689812823462613341.post-49088939844379782452011-08-24T19:58:48.338-07:002011-08-24T19:58:48.338-07:00I like the Josh Bloch Kool-Aid, but here are a cou...I like the Josh Bloch Kool-Aid, but here are a couple of alternatives.<br /><br />public List getTypeSafeList(List list, Class clazz) {<br /> for (Object o : list) {<br /> if (!clazz.isAssignableFrom(o.getClass())) {<br /> throw new ClassCastException("List contained non-strings Elements: " + o.getClass().getCanonicalName());<br /> }<br /> }<br /> return (List) list;<br /> }<br /><br /> public List getImmutableTypeSafeList(List list, Class clazz) {<br /> return Collections.unmodifiableList(getTypeSafeList(list, clazz));<br /> }<br /><br />I also took the liberty of modifying your example since the enhanced for loop will not produce null items.<br /><br /> public List getListOfStringsFromList(List list) {<br /> if ((list != null) && (list.size() > 0)) {<br /> for (Object item : list) {<br /> if (!(item instanceof String)) {<br /> throw new ClassCastException("List contained non-strings Elements: " + item.getClass().getCanonicalName());<br /> }<br /> }<br /> }<br /> return (List) list;<br /> }John Yearyhttps://www.blogger.com/profile/00461192445071361043noreply@blogger.com