Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 Copyright (C) 2016 HermeneutiX.org
    
 This file is part of SciToS.
    
 SciToS 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 3 of the License, or
 (at your option) any later version.
    
 SciToS 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 SciToS. If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.Collection;

public class Main {
    /**
     * Determine the index position of the first occurrence of the given object instance in the given collection. Thereby avoiding the use of
     * {@link Object#equals(Object) equals(Object)} and {@link Object#hashCode() hashCode()} in the {@link java.util.List#indexOf(Object)
     * indexOf(Object)} implementation of the collection/list itself.
     *
     * <p>
     * This check is supposed to be faster and can be used with objects, that are missing proper implementations of those methods. Additionally,
     * objects that are deemed {@link Object#equals(Object) equal} but not identical are ignored.
     * </p>
     *
     * @param collection
     *            collection to check for contained instance
     * @param instance
     *            specific object instance to check for
     * @param <T>
     *            type of the object to check for
     * @return position of the given instance in the collection (not just of an equal object)
     */
    public static <T> int indexOfInstance(final Collection<? extends T> collection, final T instance) {
        if (collection != null && !collection.isEmpty()) {
            int index = 0;
            for (final T collectionElement : collection) {
                if (collectionElement == instance) {
                    return index;
                }
                index++;
            }
        }
        return -1;
    }
}