Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Collections.checkedList() call for in java?

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 it's 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.

like image 669
Jay R. Avatar asked Jul 21 '09 19:07

Jay R.


People also ask

What is the use of collections class in Java?

Java Collections class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, “wrappers”, which return a new collection backed by a specified collection, and a few other odds and ends.

What is the collections package in Java?

Java Collections are the one-stop solutions for all the data manipulation jobs such as storing data, searching, sorting, insertion, deletion, and updating of data. Java collection responds as a single object, and a Java Collection Framework provides various Interfaces and Classes.

What are the three general types of collections Java?

There are three generic types of collection: ordered lists, dictionaries/maps, and sets. Ordered lists allows the programmer to insert items in a certain order and retrieve those items in the same order. An example is a waiting list. The base interfaces for ordered lists are called List and Queue.


1 Answers

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.

like image 86
Yishai Avatar answered Oct 06 '22 20:10

Yishai