Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: LGPL 

import java.util.Collections;
import java.util.Comparator;

import java.util.List;

public class Main {
    /**
     * Finds the index where an object should be inserted in a collection based
     * on the following algorithm: if the list is empty the insertion index is 0 <br/>
     * If equal element exists, the insertion index is the index of the existing
     * element+1. If multiple equal elements exist, the insertion index is after
     * the elements.
     * 
     * @param <E>
     *            type of the object
     * @param list
     *            list where the element should be inserted.
     * @param value
     *            element that should be inserted.
     * @param comparator
     *            comparator used to compare objects
     * @return index (place) where the element should be inserted.
     */
    public static <E> int findInsertionIndex(List<E> list, E object, Comparator<E> comparator) {
        // call binary search
        int binarySearchResult = Collections.binarySearch(list, object, comparator);

        int index;
        if (binarySearchResult < 0) {
            // if the result is negative turn it to positive and decrease it by
            // one (see binarySearch doc)
            index = Math.abs(binarySearchResult) - 1;
        } else {
            // if the result is positive, increase it by one
            index = binarySearchResult + 1;

            // if there are multiple equal elements iterate to find the latest
            while (index < list.size() && comparator.compare(list.get(index), object) == 0) {
                index++;
            }
        }

        return index;
    }

    /**
     * Constructs a comparator and calls findInsertionIndex(List<E> , E,
     * Comparator<E>) to find the insertion index.
     * 
     * @param <E>
     *            type of the object
     * @param list
     *            list where the element should be inserted.
     * @param value
     *            element that should be inserted.
     * @return index (place) where the element should be inserted.
     */
    public static <E extends Comparable<E>> int findInsertionIndex(List<E> list, E object) {
        Comparator<E> comparator = new Comparator<E>() {

            @Override
            public int compare(E o1, E o2) {
                return o1.compareTo(o2);
            }
        };

        return findInsertionIndex(list, object, comparator);
    }
}