![]() ![]() For this particular example, I am using Collections.emptySet(), but the principle is the same for the List and Map versions. The following sample code shows how one of these "empty" methods can be used and the image below the code demonstrates the UnsupportedOperationException that is thrown when the code execution tries to add an element to this empty collection that is immutable. As I have blogged about previously, this is useful for implementing the recommendation of Effective Java to return empty collections rather than null. In other words, the provided collection is empty and nothing can be added to it. In the case of these methods, they each return the appropriate collection type that is empty (no elements in it), typesafe, and immutable. For example, the methods Collections.emptySet(), Collections.emptyMap(), and Collections.emptyList() perform the same functionality, but on Sets, Maps, and Lists respectively. Several of the methods provided by perform similar functionality on different types of collections. There are so many highly useful methods in this class that I am going to only focus on a subset of them to keep what is already a lengthy blog posting from becoming too large. ![]() ![]() The Javadoc API documentation for explains the basics of this class such as the fact that all of its methods are static and that they all either operate on a provided collection or return a collection (here I am using " collection" more broadly to include Map as opposed to narrowly focusing on collections implementing the Collection interface). Each Java Collection interface and implementation is useful in its own right, but the Collections class provides some convenience methods that are highly useful in working with Java collections. This is not surprising considering how often I find myself using the Java Collections Framework. One of my favorite standard Java classes is the Collections class. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |