Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010 Neil Bartlett.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Neil Bartlett - initial API and implementation
 *******************************************************************************/

import java.util.List;

public class Main {
    /**
     * Move the selected items up one position in the list.
     * 
     * @param list
     *            The list of items, which will be altered in-place.
     * @param selectionIndexes
     *            The indexes of the items to be moved.
     * @return Whether any items have been moved. For example, would return false if the selected items were already at
     *         the top of the list.
     */
    public static <T> boolean moveUp(List<T> list, int[] selectionIndexes) {
        boolean moved = false;

        int size = list.size();
        for (int i = size - 1; i >= 0; i--) {
            T item = list.get(i);
            if (arrayContains(selectionIndexes, i)) {
                // Find next unselected item
                int nextUnselected = -1;
                int j = i - 1;
                while (j >= 0) {
                    if (!arrayContains(selectionIndexes, j)) {
                        nextUnselected = j;
                        break;
                    }
                    j--;
                }
                // Swap with it
                if (nextUnselected != -1) {
                    list.set(i, list.get(nextUnselected));
                    list.set(nextUnselected, item);
                    moved = true;
                }
            }
        }
        return moved;
    }

    private static boolean arrayContains(int[] array, int item) {
        for (int i : array) {
            if (i == item)
                return true;
        }
        return false;
    }
}