e5c21c41614ce8933d860c94d5a9ede90f27897a
[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.List;
13
14 /**
15  * Utility methods for lazily instantiated collections. These are useful for
16  * situations when we start off with an empty collection (where Collections.empty()
17  * can be reused), but need to add more things.
18  */
19 public final class LazyCollections {
20
21     private LazyCollections() {
22         throw new UnsupportedOperationException("Utility class should not be instantiated");
23     }
24
25     /**
26      * Add an element to a list, potentially transforming the list.
27      *
28      * @param list Current list
29      * @param obj Object that needs to be added
30      * @return new list
31      */
32     public static <T> List<T> lazyAdd(final List<T> list, final T obj) {
33         final List<T> ret;
34
35         switch (list.size()) {
36         case 0:
37             return Collections.singletonList(obj);
38         case 1:
39             ret = new ArrayList<>(2);
40             ret.addAll(list);
41             break;
42         default:
43             ret = list;
44         }
45
46         ret.add(obj);
47         return ret;
48     }
49
50 }