1 16 17 package org.apache.velocity.tools.generic; 18 19 import java.lang.reflect.Array ; 20 import java.util.List ; 21 22 56 public class ListTool { 57 58 61 public ListTool() { 62 } 63 64 77 public Object get(Object list, int index) { 78 if (this.isArray(list)) { 79 return this.getFromArray(list, index); 80 } 81 if (!this.isList(list)) { 82 return null; 83 } 84 85 try { 86 return ((List ) list).get(index); 87 } 88 catch (IndexOutOfBoundsException e) { 89 return null; 91 } 92 } 93 94 101 private Object getFromArray(Object array, int index) { 102 try { 103 return Array.get(array, index); 104 } 105 catch (IndexOutOfBoundsException e) { 106 return null; 108 } 109 } 110 111 125 public Object set(Object list, int index, Object value) { 126 if (this.isArray(list)) { 127 return this.setToArray(list, index, value); 128 } 129 if (!this.isList(list)) { 130 return null; 131 } 132 133 try { 134 ((List ) list).set(index, value); 135 return ""; 136 } 137 catch (IndexOutOfBoundsException e) { 138 return null; 140 } 141 } 142 143 151 private Object setToArray(Object array, int index, Object value) { 152 try { 153 Array.set(array, index, value); 154 return ""; 155 } 156 catch (IndexOutOfBoundsException e) { 157 return null; 159 } 160 } 161 162 175 public Integer size(Object list) { 176 if (this.isArray(list)) { 177 return new Integer (Array.getLength(list)); 179 } 180 if (!this.isList(list)) { 181 return null; 182 } 183 184 return new Integer (((List ) list).size()); 185 } 186 187 193 public boolean isArray(Object object) { 194 if (object == null) { 195 return false; 196 } 197 return object.getClass().isArray(); 198 } 199 200 206 public boolean isList(Object object) { 207 return object instanceof List ; 208 } 209 210 216 public Boolean isEmpty(Object list) { 217 Integer size = this.size(list); 218 if (size == null) { 219 return null; 220 } 221 222 return new Boolean (size.intValue() == 0); 223 } 224 225 232 public Boolean contains(Object list, Object element) { 233 if (this.isArray(list)) { 234 return this.arrayContains(list, element); 235 } 236 if (!this.isList(list)) { 237 return null; 238 } 239 240 return new Boolean (((List ) list).contains(element)); 241 } 242 243 250 private Boolean arrayContains(Object array, Object element) { 251 int size = this.size(array).intValue(); 252 253 for (int index = 0; index < size; ++index) { 254 if (this.equals(element, this.getFromArray(array, index))) { 255 return Boolean.TRUE; 256 } 257 } 258 return Boolean.FALSE; 259 } 260 261 268 private boolean equals(Object what, Object with) { 269 if (what == null) { 270 return with == null; 271 } 272 273 return what.equals(with); 274 } 275 276 } | Popular Tags |