views:

789

answers:

4

I just want to know for what java.util.Collections.checkedList() is actually used.

I have some code that I know is returning me a List<String> but its being passed through a chain of messaging calls and returned to me as a java.io.Serializable. Is that checkedList call good for me to turn my Serializable into a List<String>? I know I can cast it to a java.util.List, but I'd rather not have to check each element and I'm not comfortable with assuming each element is a String.

+2  A: 

Not quite:

Collections.checkedList will only decorate the list to prevent any future inserts with objects of the wrong class, it won't check all the elements that are already in the list.

However, you could make a new checkedList, and then call addAll and pass in the list you are unsure about - rather than writing the loop yourself.

daveb
+2  A: 

This method:

Returns a dynamically typesafe view of the specified list. Any attempt to insert an element of the wrong type will result in an immediate ClassCastException. Assuming a list contains no incorrectly typed elements prior to the time a dynamically typesafe view is generated, and that all subsequent access to the list takes place through the view, it is guaranteed that the list cannot contain an incorrectly typed element.

From the Java 1.5 API. So the call:

java.util.Collections.checkedList(yourList, List<String>);

Will generate a list that only allows the addition of Strings. As noted above, this does not guarantee the type of the original members.

pianoman
+4  A: 

It is used in part as a debugging tool to find where code inserts a class of the wrong type, in case you see that happening, but can't figure out where.

You could use it as part of a public API that provides a collection and you want to ensure the collection doesn't get anything in it of the wrong type (if for example the client erases the generics).

The way you could use it in your case is:

 Collections.checkedList(
      new ArrayList<String>(uncertainList.size()), String.class)
      .addAll(uncertainList);

If that doesn't throw an exception, then you know you are good. That isn't exactly a performance optimized piece of code, but if the list contents are reasonably small, it should be fine.

Yishai
Nice workaround!
pianoman
+3  A: 

A discussion of what checkedList could be used for is available in the documentation for checkedCollection. The reasons given are

  • as a debugging aid (if someone has used an unchecked cast)
  • to ensure safety when passing a collection to be populated by third-party code.

edit: you could use the following from google collections to check that the list does only contain strings:

Iterables.all(list, Predicates.instanceOf(String.class))

Ben Lings
Thanks. I missed that. IDEs are spoiling my javadoc reading.
Jay R.