Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.lang.reflect.Method;
import java.util.HashMap;

import java.util.Vector;

public class Main {
    /**
     * Method getHashMapFromVector.
     * @param vector Vector
     * @return HashMap
     */
    public static HashMap getHashMapFromVector(Vector vector) {
        HashMap hashMap = new HashMap(vector.size());

        for (int i = 0; i < vector.size(); i++) {
            hashMap.put(vector.elementAt(i), vector.elementAt(i));
        }

        return hashMap;
    }

    /**
     * Method getHashMapFromVector.
     * @param vector Vector
     * @param keyGetter String
     * @return HashMap
     * @throws NoSuchMethodException
     * @throws Exception
     * @throws IllegalAccessException
     */
    public static HashMap getHashMapFromVector(Vector vector, String keyGetter)
            throws NoSuchMethodException, Exception, IllegalAccessException {
        HashMap hashMap = new HashMap(vector.size());

        Object vectorElement = null;
        Object keyObject = null;
        Method keyGetterMethod = null;
        Class[] clsParms = new Class[0];
        Object[] objParms = new Object[0];

        for (int i = 0; i < vector.size(); i++) {
            vectorElement = vector.elementAt(i);

            if (vectorElement != null) {
                keyGetterMethod = vectorElement.getClass().getMethod(keyGetter, clsParms);
                keyObject = keyGetterMethod.invoke(vectorElement, objParms);
            } else {
                keyObject = null;
            }

            hashMap.put(keyObject, vectorElement);
        }

        return hashMap;
    }
}