de.tuberlin.dima.aim3.assignment1.PrimeNumbersWritable.java Source code

Java tutorial

Introduction

Here is the source code for de.tuberlin.dima.aim3.assignment1.PrimeNumbersWritable.java

Source

/**
 * AIM3 - Scalable Data Mining -  course work
 * Copyright (C) 2014  Sebastian Schelter
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package de.tuberlin.dima.aim3.assignment1;

import org.apache.hadoop.io.Writable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class PrimeNumbersWritable implements Writable {

    private int[] numbers;

    public PrimeNumbersWritable() {
        numbers = new int[0];
    }

    public PrimeNumbersWritable(int... numbers) {
        this.numbers = numbers;
    }

    @Override
    public void write(DataOutput out) throws IOException {
        //IMPLEMENT ME
        for (int i = 0; i < numbers.length; i++) {
            out.write(numbers[i]);
        }
        out.write(0);
    }

    @Override
    public void readFields(DataInput in) throws IOException {
        //IMPLEMENT ME

        List<Integer> temp = new ArrayList<Integer>();
        while (true) {
            int x = in.readByte();
            if (x == 0)
                break;
            else
                temp.add(x);
        }
        numbers = convertIntegers(temp);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof PrimeNumbersWritable) {
            PrimeNumbersWritable other = (PrimeNumbersWritable) obj;
            return Arrays.equals(numbers, other.numbers);
        }
        return false;
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(numbers);
    }

    public static int[] convertIntegers(List<Integer> integers) {
        int[] ret = new int[integers.size()];
        Iterator<Integer> iterator = integers.iterator();
        for (int i = 0; i < ret.length; i++) {
            ret[i] = iterator.next().intValue();
        }
        return ret;
    }
}