comparison flys-artifacts/src/main/java/de/intevation/flys/utils/KMIndex.java @ 3318:dbe2f85bf160

merged flys-artifacts/2.8
author Thomas Arendsen Hein <thomas@intevation.de>
date Fri, 28 Sep 2012 12:14:35 +0200
parents 0e8929d5e9e3
children 46511b4d8357
comparison
equal deleted inserted replaced
2987:98c7a46ec5ae 3318:dbe2f85bf160
1 package de.intevation.flys.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 public class KMIndex<A>
11 implements Serializable, Iterable<KMIndex.Entry<A>>
12 {
13 public static final double EPSILON = 1e-4;
14
15 public static class Entry<A>
16 implements Serializable, Comparable<Entry<A>>
17 {
18 protected double km;
19 protected A value;
20
21 public Entry(double km) {
22 this.km = km;
23 }
24
25 public Entry(double km, A value) {
26 this.km = km;
27 this.value = value;
28 }
29
30 public double getKm() {
31 return km;
32 }
33
34 public A getValue() {
35 return value;
36 }
37
38 public void setValue(A value) {
39 this.value = value;
40 }
41
42 @Override
43 public int compareTo(Entry<A> other) {
44 double diff = km - other.km;
45 if (diff < -EPSILON) return -1;
46 if (diff > +EPSILON) return +1;
47 return 0;
48 }
49
50 public boolean epsilonEquals(double km) {
51 return Math.abs(this.km - km) < EPSILON;
52 }
53 } // class Entry
54
55
56 protected List<Entry<A>> entries;
57
58 public KMIndex() {
59 this(10);
60 }
61
62 public KMIndex(int capacity) {
63 entries = new ArrayList<Entry<A>>(capacity);
64 }
65
66 public void add(double km, A value) {
67 entries.add(new Entry<A>(km, value));
68 }
69
70 public void sort() {
71 Collections.sort(entries);
72 }
73
74 public Entry<A> search(double km) {
75 for (Entry<A> entry: entries) {
76 if (entry.epsilonEquals(km)) {
77 return entry;
78 }
79 }
80 return null;
81 }
82
83 public Entry<A> binarySearch(double km) {
84 int index = Collections.binarySearch(entries, new Entry<A>(km));
85 return index >= 0 ? entries.get(index) : null;
86 }
87
88 public Iterator<Entry<A>> iterator() {
89 return entries.iterator();
90 }
91 }
92 // vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :

http://dive4elements.wald.intevation.org