Debian Codegraph @

hppc-examples/src/test/java/com/carrotsearch/hppc/examples/HppcExample_003_IteratingOverSets.java

raw
1 package com.carrotsearch.hppc.examples;
2
3 import static com.carrotsearch.hppc.examples.Helpers.*;
4 import static org.assertj.core.api.Assertions.*;
5
6 import org.junit.Before;
7 import org.junit.Test;
8
9 import com.carrotsearch.hppc.IntHashSet;
10 import com.carrotsearch.hppc.IntScatterSet;
11 import com.carrotsearch.hppc.cursors.IntCursor;
12 import com.carrotsearch.hppc.procedures.IntProcedure;
13
14 /**
15 * Examples of how to iterate over HPPC sets.
16 */
17 public class HppcExample_003_IteratingOverSets {
18
19 public IntHashSet hashSet;
20 public IntScatterSet scatterSet;
21
22 @Before
23 public void setup() {
24 // Note that copying the other way around wouldn't be safe (and is thus impossible
25 // because there is no IntScatterSet constructor that can copy keys from another
26 // container).
27 scatterSet = IntScatterSet.from(1, 1, 2, 3, 5, 0);
28 hashSet = new IntHashSet(scatterSet);
29 }
30
31 /**
32 * All sets implement the {@link Iterable} interface that returns a "cursor"
33 * object that moves over the container's elements. The cursor object remains
34 * identical for the entire iteration (very little memory overhead).
35 *
36 * The cursor's index points at the underlying buffer's position of a
37 * given element, the cursor's value is the element itself.
38 */
39 @Test
40 public void cursor() {
41 for (IntCursor c : scatterSet) {
42 printfln("scatterSet contains %d (at buffer index %d)", c.value, c.index);
43 assertThat(c.value).isEqualTo(scatterSet.keys[c.index]);
44 }
45
46 for (IntCursor c : hashSet) {
47 printfln("hashSet contains %d (at buffer index %d)", c.value, c.index);
48 assertThat(c.value).isEqualTo(hashSet.keys[c.index]);
49 }
50 }
51
52 /**
53 * A for-each type loop with an anonymous class.
54 */
55 @Test
56 public void forEachLoop() {
57 scatterSet.forEach(new IntProcedure() {
58 @Override
59 public void apply(int value) {
60 printfln("scatterSet contains %d", value);
61 }
62 });
63
64 hashSet.forEach(new IntProcedure() {
65 @Override
66 public void apply(int value) {
67 printfln("hashSet contains %d", value);
68 }
69 });
70 }
71 }