comparison flys-artifacts/src/main/java/de/intevation/flys/utils/KMIndex.java @ 3013:ba62c1751f07

FixA: Added new serializable km inedx structure. flys-artifacts/trunk@4578 c6561f87-3c4e-4783-a992-168aeb5c3f6f
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Tue, 05 Jun 2012 09:04:01 +0000
parents
children 65b6e27c6f25
comparison
equal deleted inserted replaced
3012:0330bff1b382 3013:ba62c1751f07
1 package de.intevation.flys.utils;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.List;
6
7 import java.io.Serializable;
8
9 public class KMIndex<A>
10 implements Serializable
11 {
12 public static final double EPSILON = 1e-4;
13
14 public static class Entry<A>
15 implements Serializable, Comparable<Entry<A>>
16 {
17 protected double km;
18 protected A value;
19
20 public Entry(double km) {
21 this.km = km;
22 }
23
24 public Entry(double km, A value) {
25 this.km = km;
26 this.value = value;
27 }
28
29 public double getKm() {
30 return km;
31 }
32
33 public A getValue() {
34 return value;
35 }
36
37 public void setValue(A value) {
38 this.value = value;
39 }
40
41 @Override
42 public int compareTo(Entry<A> other) {
43 double diff = km - other.km;
44 if (diff < -EPSILON) return -1;
45 if (diff > +EPSILON) return +1;
46 return 0;
47 }
48
49 public boolean epsilonEquals(double km) {
50 return Math.abs(this.km - km) < EPSILON;
51 }
52 } // class Entry
53
54
55 protected List<Entry<A>> entries;
56
57 public KMIndex() {
58 this(10);
59 }
60
61 public KMIndex(int capacity) {
62 entries = new ArrayList<Entry<A>>(capacity);
63 }
64
65 public void add(double km, A value) {
66 entries.add(new Entry(km, value));
67 }
68
69 public void sort() {
70 Collections.sort(entries);
71 }
72
73 public Entry<A> search(double km) {
74 for (Entry<A> entry: entries) {
75 if (entry.epsilonEquals(km)) {
76 return entry;
77 }
78 }
79 return null;
80 }
81
82 public Entry<A> binarySearch(double km) {
83 int index = Collections.binarySearch(entries, new Entry(km));
84 return index >= 0 ? entries.get(index) : null;
85 }
86 }
87 // vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :

http://dive4elements.wald.intevation.org