Java List Swap swapItems(final List data, int from, int to)

Here you can find the source of swapItems(final List data, int from, int to)

Description

Swaps 2 items

License

Apache License

Parameter

Parameter Description
data a parameter
from a parameter
to a parameter

Declaration

public static <T> void swapItems(final List<T> data, int from, int to) 

Method Source Code

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

import java.util.Collection;

import java.util.List;
import java.util.Map;

public class Main {
    /**/*from  w  ww.ja  v a2 s .c o m*/
     * Swaps 2 items
     * 
     * @param data
     * @param from
     * @param to
     */
    public static <T> void swapItems(final List<T> data, int from, int to) {
        if (from == to)
            return;
        if (!hasElements(data))
            return;
        if (from < 0 || from >= data.size()) {
            throw new IllegalArgumentException("'from' must be within 0 to n-1");
        }
        if (to < 0 || to >= data.size()) {
            throw new IllegalArgumentException("'to' must be within 0 to n-1");
        }

        T temp = data.get(from);
        data.set(from, data.get(to));
        data.set(to, temp);
    }

    /**
     * Checks whether the COLLECTION is not NULL and has at least one element.
     * 
     * @param <T>
     *            the generic type
     * @param collection
     *            the collection
     * @return true, if successful
     */
    public static <T> boolean hasElements(Collection<T> collection) {
        return (null != collection && collection.size() > 0);
    }

    /**
     * Checks whether the MAP is not NULL and has at least one element.
     * 
     * @param <T>
     *            the generic type
     * @param <V>
     *            the value type
     * @param map
     *            the map
     * @return true, if successful
     */
    public static <T, V> boolean hasElements(Map<T, V> map) {
        return (null != map && map.size() > 0);
    }
}

Related

  1. swap(List items, int index1_, int index2_)
  2. swap(List list, int i1, int i2)
  3. swap(List list, int index1, int index2)
  4. swap(List list, int minIndex, int maxIndex)
  5. swapElements(List list, T element1, T element2)
  6. swapListElements(List list, int idx1, int idx2)