1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * https://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package org.apache.commons.jexl3.internal.introspection;
19
20 import java.lang.reflect.Array;
21 import java.util.Iterator;
22 import java.util.NoSuchElementException;
23
24 /**
25 * <p>
26 * An Iterator wrapper for an Object[]. This will
27 * allow us to deal with all array like structures
28 * in a consistent manner.
29 * </p>
30 * <p>
31 * WARNING : this class's operations are NOT synchronized.
32 * It is meant to be used in a single thread, newly created
33 * for each use in the #foreach() directive.
34 * If this is used or shared, synchronize in the
35 * next() method.
36 * </p>
37 *
38 * @since 1.0
39 */
40 public class ArrayIterator implements Iterator<Object> {
41
42 /** The objects to iterate over. */
43 private final Object array;
44
45 /** The size of the array. */
46 private final int size;
47
48 /** The current position and size in the array. */
49 private int pos;
50
51 /**
52 * Creates a new iterator instance for the specified array.
53 *
54 * @param arr The array for which an iterator is desired.
55 */
56 public ArrayIterator(final Object arr) {
57 if (arr == null) {
58 array = null;
59 pos = 0;
60 size = 0;
61 } else if (!arr.getClass().isArray()) {
62 throw new IllegalArgumentException(arr.getClass() + " is not an array");
63 } else {
64 array = arr;
65 pos = 0;
66 size = Array.getLength(array);
67 }
68 }
69
70 /**
71 * Check to see if there is another element in the array.
72 *
73 * @return Whether there is another element.
74 */
75 @Override
76 public boolean hasNext() {
77 return pos < size;
78 }
79
80 /**
81 * Move to next element in the array.
82 *
83 * @return The next object in the array.
84 */
85 @Override
86 public Object next() {
87 if (pos < size) {
88 return Array.get(array, pos++);
89 }
90 // we screwed up...
91 throw new NoSuchElementException("No more elements: " + pos
92 + " / " + size);
93 }
94 }