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.Int2IntMap;
22
23 import java.io.DataInput;
24 import java.io.DataOutput;
25 import java.io.IOException;
26
27 import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
28 import it.unimi.dsi.fastutil.objects.ObjectIterator;
29
30 import org.apache.hadoop.io.Writable;
31
32
33
34
35 public class IntSparseVector implements Writable {
36
37
38
39 private Int2IntOpenHashMap entries = null;
40
41
42
43
44 public IntSparseVector() {
45 initialize(Int2IntOpenHashMap.DEFAULT_INITIAL_SIZE);
46 }
47
48
49
50
51
52
53 public IntSparseVector(int size) {
54 initialize(size);
55 }
56
57
58
59
60
61
62 private void initialize(int size) {
63 entries = new Int2IntOpenHashMap(size);
64 entries.defaultReturnValue(0);
65 }
66
67
68
69
70
71
72
73 public int get(int i) {
74 return entries.get(i);
75 }
76
77
78
79
80
81
82
83 public void set(int i, int value) {
84 entries.put(i, value);
85 }
86
87
88
89
90 public void clear() {
91 entries.clear();
92 }
93
94
95
96
97
98
99
100 public void add(IntSparseVector other) {
101 ObjectIterator<Int2IntMap.Entry> iter =
102 other.entries.int2IntEntrySet().fastIterator();
103 while (iter.hasNext()) {
104 Int2IntMap.Entry entry = iter.next();
105 entries.addTo(entry.getIntKey(), entry.getIntValue());
106 }
107 }
108
109 @Override
110 public void write(DataOutput out) throws IOException {
111 out.writeInt(entries.size());
112 ObjectIterator<Int2IntMap.Entry> iter =
113 entries.int2IntEntrySet().fastIterator();
114 while (iter.hasNext()) {
115 Int2IntMap.Entry entry = iter.next();
116 out.writeInt(entry.getIntKey());
117 out.writeInt(entry.getIntValue());
118 }
119 }
120
121 @Override
122 public void readFields(DataInput in) throws IOException {
123 int size = in.readInt();
124 initialize(size);
125 for (int i = 0; i < size; ++i) {
126 int row = in.readInt();
127 int value = in.readInt();
128 entries.put(row, value);
129 }
130 }
131 }