1 | /** |
---|
2 | * Licensed to the Apache Software Foundation (ASF) under one |
---|
3 | * or more contributor license agreements. See the NOTICE file |
---|
4 | * distributed with this work for additional information |
---|
5 | * regarding copyright ownership. The ASF licenses this file |
---|
6 | * to you under the Apache License, Version 2.0 (the |
---|
7 | * "License"); you may not use this file except in compliance |
---|
8 | * with the License. You may obtain a copy of the License at |
---|
9 | * |
---|
10 | * http://www.apache.org/licenses/LICENSE-2.0 |
---|
11 | * |
---|
12 | * Unless required by applicable law or agreed to in writing, software |
---|
13 | * distributed under the License is distributed on an "AS IS" BASIS, |
---|
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
---|
15 | * See the License for the specific language governing permissions and |
---|
16 | * limitations under the License. |
---|
17 | */ |
---|
18 | package org.apache.hadoop.util; |
---|
19 | |
---|
20 | import java.util.ArrayList; |
---|
21 | import java.util.Arrays; |
---|
22 | import java.util.List; |
---|
23 | import java.util.Map; |
---|
24 | import java.util.NavigableMap; |
---|
25 | import java.util.TreeMap; |
---|
26 | |
---|
27 | public class TestCyclicIteration extends junit.framework.TestCase { |
---|
28 | public void testCyclicIteration() throws Exception { |
---|
29 | for(int n = 0; n < 5; n++) { |
---|
30 | checkCyclicIteration(n); |
---|
31 | } |
---|
32 | } |
---|
33 | |
---|
34 | private static void checkCyclicIteration(int numOfElements) { |
---|
35 | //create a tree map |
---|
36 | final NavigableMap<Integer, Integer> map = new TreeMap<Integer, Integer>(); |
---|
37 | final Integer[] integers = new Integer[numOfElements]; |
---|
38 | for(int i = 0; i < integers.length; i++) { |
---|
39 | integers[i] = 2*i; |
---|
40 | map.put(integers[i], integers[i]); |
---|
41 | } |
---|
42 | System.out.println("\n\nintegers=" + Arrays.asList(integers)); |
---|
43 | System.out.println("map=" + map); |
---|
44 | |
---|
45 | //try starting everywhere |
---|
46 | for(int start = -1; start <= 2*integers.length - 1; start++) { |
---|
47 | //get a cyclic iteration |
---|
48 | final List<Integer> iteration = new ArrayList<Integer>(); |
---|
49 | for(Map.Entry<Integer, Integer> e : new CyclicIteration<Integer, Integer>(map, start)) { |
---|
50 | iteration.add(e.getKey()); |
---|
51 | } |
---|
52 | System.out.println("start=" + start + ", iteration=" + iteration); |
---|
53 | |
---|
54 | //verify results |
---|
55 | for(int i = 0; i < integers.length; i++) { |
---|
56 | final int j = ((start+2)/2 + i)%integers.length; |
---|
57 | assertEquals("i=" + i + ", j=" + j, iteration.get(i), integers[j]); |
---|
58 | } |
---|
59 | } |
---|
60 | } |
---|
61 | } |
---|