1/*2 * Licensed to the Apache Software Foundation (ASF) under one3 * or more contributor license agreements. See the NOTICE file4 * distributed with this work for additional information5 * regarding copyright ownership. The ASF licenses this file6 * to you under the Apache License, Version 2.0 (the7 * "License"); you may not use this file except in compliance8 * with the License. You may obtain a copy of the License at9 *10 * http://www.apache.org/licenses/LICENSE-2.011 *12 * Unless required by applicable law or agreed to in writing, software13 * distributed under the License is distributed on an "AS IS" BASIS,14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15 * See the License for the specific language governing permissions and16 * limitations under the License.17 */18package org.apache.giraph.utils;
1920import java.io.DataInput;
21import java.io.DataOutput;
22import java.io.IOException;
23import java.lang.reflect.Array;
2425import org.apache.hadoop.io.Writable;
26import org.apache.hadoop.io.WritableFactories;
2728import com.google.common.base.Preconditions;
2930/**31 * A Writable for arrays containing instances of a class. The elements of this32 * writable must all be instances of the same class.33 *34 * @param <T> element type35 */36publicclass ArrayWritable<T extends Writable> implements Writable {
37/** Element type class */38private Class<T> valueClass;
39/** Array */40private T[] values;
4142/** Constructor */43publicArrayWritable() {
44 }
4546/**47 * Constructor48 * @param valueClass Element type class49 * @param values Array of elements50 */51publicArrayWritable(Class<T> valueClass, T[] values) {
52 Preconditions.checkNotNull(valueClass,
53"valueClass cannot be null in ArrayWritable");
54this.valueClass = valueClass;
55this.values = values;
56 }
5758/**59 * Get element type class60 * @return element type class61 */62public Class<T> getValueClass() {
63return valueClass;
64 }
6566/**67 * Set array68 * @param values array69 */70publicvoid set(T[] values) { this.values = values; }
7172/**73 * Ger array74 * @return array75 */76public T[] get() { return values; }
7778 @Override
79publicvoid readFields(DataInput in) throws IOException {
80 valueClass = WritableUtils.readClass(in);
81 values = (T[]) Array.newInstance(valueClass, in.readInt());
8283for (int i = 0; i < values.length; i++) {
84 T value = (T) WritableFactories.newInstance(valueClass);
85 value.readFields(in); // read a value86 values[i] = value; // store it in values87 }
88 }
8990 @Override
91publicvoid write(DataOutput out) throws IOException {
92 Preconditions.checkNotNull(valueClass,
93"valueClass cannot be null in ArrayWritable");
94 WritableUtils.writeClass(valueClass, out);
95 out.writeInt(values.length); // write values96for (int i = 0; i < values.length; i++) {
97 values[i].write(out);
98 }
99 }
100 }