1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.giraph.aggregators.matrix.sparse;
20
21 import it.unimi.dsi.fastutil.ints.Int2LongMap;
22 import it.unimi.dsi.fastutil.ints.Int2LongOpenHashMap;
23 import it.unimi.dsi.fastutil.objects.ObjectIterator;
24
25 import java.io.DataInput;
26 import java.io.DataOutput;
27 import java.io.IOException;
28
29 import org.apache.hadoop.io.Writable;
30
31
32
33
34 public class LongSparseVector implements Writable {
35
36
37
38 private Int2LongOpenHashMap entries = null;
39
40
41
42
43 public LongSparseVector() {
44 initialize(Int2LongOpenHashMap.DEFAULT_INITIAL_SIZE);
45 }
46
47
48
49
50
51
52 public LongSparseVector(int size) {
53 initialize(size);
54 }
55
56
57
58
59
60
61 private void initialize(int size) {
62 entries = new Int2LongOpenHashMap(size);
63 entries.defaultReturnValue(0L);
64 }
65
66
67
68
69
70
71
72 public long get(int i) {
73 return entries.get(i);
74 }
75
76
77
78
79
80
81
82 public void set(int i, long value) {
83 entries.put(i, value);
84 }
85
86
87
88
89
90
91 public void add(int key, long value) {
92 entries.addTo(key, value);
93 }
94
95
96
97
98 public void clear() {
99 entries.clear();
100 }
101
102
103
104
105
106
107
108 public void add(LongSparseVector other) {
109 ObjectIterator<Int2LongMap.Entry> iter =
110 other.entries.int2LongEntrySet().fastIterator();
111 while (iter.hasNext()) {
112 Int2LongMap.Entry entry = iter.next();
113 entries.addTo(entry.getIntKey(), entry.getLongValue());
114 }
115 }
116
117 @Override
118 public void write(DataOutput out) throws IOException {
119 out.writeInt(entries.size());
120 ObjectIterator<Int2LongMap.Entry> iter =
121 entries.int2LongEntrySet().fastIterator();
122 while (iter.hasNext()) {
123 Int2LongMap.Entry entry = iter.next();
124 out.writeInt(entry.getIntKey());
125 out.writeLong(entry.getLongValue());
126 }
127 }
128
129 @Override
130 public void readFields(DataInput in) throws IOException {
131 int size = in.readInt();
132 initialize(size);
133 for (int i = 0; i < size; ++i) {
134 int row = in.readInt();
135 long value = in.readLong();
136 entries.put(row, value);
137 }
138 }
139 }