Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * Copyright (C) 2012 Davide Mottin <mottin@disi.unitn.eu>
 *
 * 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 2
 * 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

import java.util.ArrayList;

import java.util.Collection;

import java.util.HashSet;

import java.util.List;

import java.util.Set;

public class Main {
    /**
     * Produce a new set
     * @param <T>
     * @param set1
     * @param set2
     * @return 
     */
    public static <T> Set<T> intersect(Set<T> set1, Set<T> set2) {
        Set<T> a;
        Set<T> b;

        if (set1.size() <= set2.size()) {
            a = set1;
            b = set2;
        } else {
            a = set2;
            b = set1;
        }
        Set<T> intersection = new HashSet<>(a.size() * 4 / 3);
        for (T e : a) {
            if (b.contains(e)) {
                intersection.add(e);
            }
        }
        return intersection;
    }

    /**
     * Produce a new set
     * @param <T>
     * @param set1
     * @param set2
     * @return 
     */
    public static <T> Set<T> intersect(Set<T> set1, Collection<T> set2) {
        Set<T> intersection = new HashSet<>(set1.size() * 4 / 3);
        for (T e : set2) {
            if (set1.contains(e)) {
                intersection.add(e);
            }
        }
        return intersection;
    }

    public static <T> List<T> intersect(List<T> list1, Set<T> set2) {
        List<T> intersection = new ArrayList<>(set2.size());

        for (T e : list1) {
            if (set2.contains(e)) {
                intersection.add(e);
            }
        }
        return intersection;
    }

    public static <T> List<T> intersect(List<T> list1, List<T> list2) {
        List<T> a;
        List<T> b;
        List<T> intersection;
        if (list1.size() <= list2.size()) {
            a = list1;
            b = list2;
            intersection = new ArrayList<>(list1.size());
        } else {
            a = list2;
            b = list1;
            intersection = new ArrayList<>(list2.size());
        }
        for (T e : a) {
            if (b.contains(e)) {
                intersection.add(e);
            }
        }
        return intersection;
    }
}