Let's start by explaining what the benefits are:
1, if you want to new an empty list, and this list will not add elements later, then use Collections.emptylist () good.
New ArrayList () or new LinkedList () will have an initial size at the time of creation and will occupy a memory.
Every use of new an empty list collection, waste is a big one, waste is serious, it is not good
2, in order to encode the convenience.
For example, a method return type is list, and when there is no result, returns NULL, returns the list of lists when there is a result.
In that case, a null judgment is required where this method is called. Using a method like Emptylist, you can make it easy for the method caller. The returned will not be null, eliminating the duplication of code.
Note the place:
This empty collection is not called. Add (), add element. Because the direct report is abnormal. Because the source code is so written: direct throw exception.
Well, collections didn't write that, but Emptylist inherited Abstractlist, a simple way to implement a partial set of frames.
The method in which the Add method is finally called is the direct throw exception.
throw new Unsupportedoperationexception ();
This explains the exception to the Add report.
Here is a simple look at the source code:
[Java]View PlainCopy
- /**
- * Collections class inside the method is as follows, step by step look down
- */
- public static final <T> list<t> emptylist () {
- return (list<t>) empty_list;
- }
- 。。。。。
- /**
- * Collections class inside the method is as follows, step by step look down
- */
- public static final List empty_list = new emptylist<> ();
- 。。。。。
- /**
- * A static inner class inside the collections
- */
- private static class emptylist<e> extends Abstractlist<e> implements Randomaccess, Serializable {
- private Static final long serialversionuid = 8842843931221139166L;
- Public iterator<e> Iterator () {
- return Emptyiterator ();
- }
- Public listiterator<e> Listiterator () {
- return Emptylistiterator ();
- }
- public int size () {return 0;}
- Public Boolean isEmpty () {return true;}
- Public Boolean contains (Object obj) {return false;}
- Public Boolean containsall (collection<?> c) { return c.isempty ();}
- Public object[] ToArray () { return new object[0];}
- Public <T> t[] ToArray (t[] a) {
- if (A.length > 0)
- a[0] = null;
- return A;
- }
- Public E Get (int index) {
- throw New Indexoutofboundsexception ("Index:" +index);
- }
- public Boolean equals (Object o) {
- return (o instanceof List) && ((list<?>) O). IsEmpty ();
- }
- public int hashcode () { return 1;}
- //Preserves singleton property
- private Object Readresolve () {
- return empty_list;
- }
- }
In addition to this emptylist, there are similar, emptymap,emptyset and so on. Specifically, it's all a routine.
The role and benefits of Java Collections.emptylist (), Emptyset (), Emptymap (), and the areas to be noted