Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.util.*;

public class Main {
    /**
     * Answer the junction between a and b. Answer is of the same type as a.
     * 
     * @param a
     * @param b
     * @return
     */
    public static Collection junction(Collection a, Collection b) {
        Collection answer = createCollection(a);
        for (Iterator i = a.iterator(); i.hasNext();) {
            Object oa = i.next();
            for (Iterator k = b.iterator(); k.hasNext();) {
                Object ob = k.next();
                if (oa.equals(ob)) {
                    answer.add(oa);
                }
            }
        }
        return answer;
    }

    /**
     * Create and answer a collection that is the same type, or the closest
     * equivalent of col.
     * 
     * @param col
     * @return
     */
    public static Collection createCollection(Collection col) {
        Collection answer;
        try {
            answer = (Collection) col.getClass().newInstance();
        } catch (Exception e) {
            if (col instanceof List) {
                answer = new ArrayList();
            } else if (col instanceof SortedSet) {
                answer = new TreeSet();
            } else if (col instanceof Set) {
                answer = new HashSet();
            } else {
                answer = new ArrayList(); // should this throw an exception?
            }
        }
        return answer;
    }
}