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