Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/**
 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
 */

import java.lang.reflect.Array;
import java.util.ArrayList;

import java.util.Collection;

import java.util.HashSet;

import java.util.List;

import java.util.Set;

public class Main {
    /**
     * Add elements from the source to the target as long as they don't already
     * exist there. Return the number of items actually added.
     *
     * @param source
     * @param target
     * @return int
     */
    public static <T> int addWithoutDuplicates(Collection<T> source, Collection<T> target) {

        int added = 0;

        for (T item : source) {
            if (target.contains(item)) {
                continue;
            }
            target.add(item);
            added++;
        }

        return added;
    }

    /**
     * If the newValue is already held within the values array then the values
     * array is returned, otherwise a new array is created appending the
     * newValue to the end.
     *
     * @param <T>
     * @param values
     * @param newValue
     * @return an array containing the union of values and newValue
     */
    @Deprecated
    public static <T> T[] addWithoutDuplicates(T[] values, T newValue) {

        for (T value : values) {
            if (value.equals(newValue)) {
                return values;
            }
        }

        T[] largerOne = (T[]) Array.newInstance(values.getClass().getComponentType(), values.length + 1);
        System.arraycopy(values, 0, largerOne, 0, values.length);
        largerOne[values.length] = newValue;
        return largerOne;
    }

    /**
     * Returns an array of values as a union set of the two input arrays.
     *
     * @param <T>
     * @param values
     * @param newValues
     * @return the union of the two arrays
     */
    @Deprecated
    public static <T> T[] addWithoutDuplicates(T[] values, T[] newValues) {

        Set<T> originals = new HashSet<>(values.length);
        for (T value : values) {
            originals.add(value);
        }
        List<T> newOnes = new ArrayList<>(newValues.length);
        for (T value : newValues) {
            if (originals.contains(value)) {
                continue;
            }
            newOnes.add(value);
        }

        T[] largerOne = (T[]) Array.newInstance(values.getClass().getComponentType(),
                values.length + newOnes.size());
        System.arraycopy(values, 0, largerOne, 0, values.length);
        for (int i = values.length; i < largerOne.length; i++) {
            largerOne[i] = newOnes.get(i - values.length);
        }
        return largerOne;
    }
}