Decouple HashCodeBuilder from Builder
[yangtools.git] / common / util / src / main / java / org / opendaylight / yangtools / util / LazyCollections.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.util;
9
10 import java.util.ArrayList;
11 import java.util.Collections;
12 import java.util.HashSet;
13 import java.util.List;
14 import java.util.Set;
15
16 /**
17  * Utility methods for lazily instantiated collections. These are useful for situations when we start off with an empty
18  * collection (where Collections.empty() * can be reused), but need to add more things.
19  */
20 public final class LazyCollections {
21     private LazyCollections() {
22         // Hidden on purpose
23     }
24
25     /**
26      * Add an element to a list, potentially transforming the list.
27      *
28      * @param <E> the type of elements in the list
29      * @param list Current list
30      * @param obj Object that needs to be added
31      * @return new list
32      */
33     public static <E> List<E> lazyAdd(final List<E> list, final E obj) {
34         final List<E> ret;
35
36         switch (list.size()) {
37             case 0:
38                 return Collections.singletonList(obj);
39             case 1:
40                 ret = new ArrayList<>(2);
41                 ret.addAll(list);
42                 break;
43             default:
44                 ret = list;
45         }
46
47         ret.add(obj);
48         return ret;
49     }
50
51     /**
52      * Add an element to a set, potentially transforming the set.
53      *
54      * @param <E> the type of elements in the set
55      * @param set Current set
56      * @param obj Object that needs to be added
57      * @return new set
58      */
59     public static <E> Set<E> lazyAdd(final Set<E> set, final E obj) {
60         final Set<E> ret;
61
62         switch (set.size()) {
63             case 0:
64                 return Collections.singleton(obj);
65             case 1:
66                 ret = new HashSet<>(4);
67                 ret.addAll(set);
68                 break;
69             default:
70                 ret = set;
71         }
72
73         ret.add(obj);
74         return ret;
75     }
76 }