comparison artifacts/src/main/java/org/dive4elements/river/utils/KMIndex.java @ 5838:5aa05a7a34b7

Rename modules to more fitting names.
author Sascha L. Teichmann <teichmann@intevation.de>
date Thu, 25 Apr 2013 15:23:37 +0200
parents flys-artifacts/src/main/java/org/dive4elements/river/utils/KMIndex.java@bd047b71ab37
children 4897a58c8746
comparison
equal deleted inserted replaced
5837:d9901a08d0a6 5838:5aa05a7a34b7
1 package org.dive4elements.river.utils;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.List;
6 import java.util.Iterator;
7
8 import java.io.Serializable;
9
10 /** km to value, searchable. Tolerance is at 10cm. */
11 public class KMIndex<A>
12 implements Serializable, Iterable<KMIndex.Entry<A>>
13 {
14 public static final double EPSILON = 1e-4;
15
16 public static class Entry<A>
17 implements Serializable, Comparable<Entry<A>>
18 {
19 protected double km;
20 protected A value;
21
22 public Entry(double km) {
23 this.km = km;
24 }
25
26 public Entry(double km, A value) {
27 this.km = km;
28 this.value = value;
29 }
30
31 public double getKm() {
32 return km;
33 }
34
35 public A getValue() {
36 return value;
37 }
38
39 public void setValue(A value) {
40 this.value = value;
41 }
42
43 @Override
44 public int compareTo(Entry<A> other) {
45 double diff = km - other.km;
46 if (diff < -EPSILON) return -1;
47 if (diff > +EPSILON) return +1;
48 return 0;
49 }
50
51 public boolean epsilonEquals(double km) {
52 return Math.abs(this.km - km) < EPSILON;
53 }
54 } // class Entry
55
56
57 protected List<Entry<A>> entries;
58
59 public KMIndex() {
60 this(10);
61 }
62
63 public KMIndex(int capacity) {
64 entries = new ArrayList<Entry<A>>(capacity);
65 }
66
67 public void add(double km, A value) {
68 entries.add(new Entry<A>(km, value));
69 }
70
71 public void sort() {
72 Collections.sort(entries);
73 }
74
75 public Entry<A> search(double km) {
76 for (Entry<A> entry: entries) {
77 if (entry.epsilonEquals(km)) {
78 return entry;
79 }
80 }
81 return null;
82 }
83
84 public Entry<A> binarySearch(double km) {
85 int index = Collections.binarySearch(entries, new Entry<A>(km));
86 return index >= 0 ? entries.get(index) : null;
87 }
88
89 public Iterator<Entry<A>> iterator() {
90 return entries.iterator();
91 }
92 }
93 // vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :

http://dive4elements.wald.intevation.org