View Javadoc
1   /*
2    * Copyright 2010 Daniel Kurka
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5    * use this file except in compliance with the License. You may obtain a copy of
6    * the License at
7    * 
8    * http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations under
14   * the License.
15   */
16  package com.googlecode.mgwt.collection.shared.java;
17  
18  import java.util.ArrayList;
19  import java.util.Set;
20  
21  import com.googlecode.mgwt.collection.shared.LightArray;
22  
23  /**
24   * An implementation of {@link LightArray} used on the jvm
25   * 
26   * @author Daniel Kurka
27   * 
28   * @param <T>
29   */
30  public class JavaLightArray<T> implements LightArray<T> {
31  
32  	private ArrayList<T> list;
33  
34    /**
35     * Construct a {@link JavaLightArray}
36     */
37  	public JavaLightArray() {
38  		list = new ArrayList<T>();
39  	}
40  
41  	@Override
42  	public T shift() {
43  		return list.remove(0);
44  	}
45  
46  	@Override
47  	public T get(int index) {
48  		// behave like js!
49  		if (index < 0 || index >= list.size())
50  			return null;
51  		return list.get(index);
52  	}
53  
54  	@Override
55  	public void set(int index, T value) {
56  		// behave like js!
57  		if (index < 0)
58  			return;
59  		if (index >= list.size()) {
60  			for (int i = list.size(); i < index; i++) {
61  				list.add(null);
62  			}
63  			list.add(value);
64  		} else {
65  			list.set(index, value);
66  		}
67  
68  	}
69  
70  	@Override
71  	public int length() {
72  		return list.size();
73  	}
74  
75  	@Override
76  	public void unshift(T value) {
77  		list.add(0, value);
78  
79  	}
80  
81  	@Override
82  	public void push(T value) {
83  		list.add(value);
84  
85  	}
86  
87    /**
88     * Construct a {@link JavaLightArray} from a set
89     * 
90     * @param <T> the types to store in the array
91     * @param set the set with the initial values
92     * @return the new array
93     */
94  	public static <T> JavaLightArray<T> fromSet(Set<T> set) {
95  		JavaLightArray<T> array = new JavaLightArray<T>();
96  		for (T t : set) {
97  			array.push(t);
98  		}
99  		return array;
100 	}
101 
102 }