Java:获取数组中的子数组的多种方法

Java:从一个数组中创建子数组

使用Arrays.copyOfRange函数

Arrays.copyOfRange支持:boolean[], byte[] ,char[],double[],float[],int[],long[]以及泛型的 T[]
使用示例如下:

import java.util.Arrays;

public class hello {
    public static void main(String[] args) {
        int[] src = new int[]{1, 2, 3, 4, 5};
        int newArray[] = Arrays.copyOfRange(src, 0, 2);
        for (int i : newArray) {
            System.out.println(i);
        }
    }
}

官方文档如下:

copyOfRange
public static <T> T[] copyOfRange(T[] original,
                                  int from,
                                  int to)
Copies the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and original.length, inclusive. The value at original[from] is placed into the initial element of the copy (unless from == original.length or from == to). Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to), which must be greater than or equal to from, may be greater than original.length, in which case null is placed in all elements of the copy whose index is greater than or equal to original.length - from. The length of the returned array will be to - from.
The resulting array is of exactly the same class as the original array.

Parameters:
	original - the array from which a range is to be copied
from - the initial index of the range to be copied, inclusive
to - the final index of the range to be copied, exclusive. (This index may lie outside the array.)
Returns:
	a new array containing the specified range from the original array, truncated or padded with nulls to obtain the required length
Throws:
	ArrayIndexOutOfBoundsException - if from < 0 or from > original.length()
	IllegalArgumentException - if from > to
	NullPointerException - if original is null
Since:
	1.6

使用subList

对于List来说,可以使用subList获取子列表
注意:subList返回的是原列表的一个视图,它所有的操作最终都会作用在原列表上
示例如下:

import java.util.ArrayList;

public class hello {
    public static void main(String[] args) {
        // create an empty array list
        ArrayList<String> color_list = new ArrayList<String>();

        // use add() method to add values in the list
        color_list.add("White");
        color_list.add("Black");
        color_list.add("Red");
        System.out.println("List of the colors :" + color_list);

        //Return portion of the list : fromindex(inclusive)->1,  toindex(exclusive)->3
        ArrayList<String> new_color_list1 = new ArrayList<String>(color_list.subList(1, 3));
        System.out.println("Portion of the list: " + new_color_list1);
    }
}

官方文档如下:

public List<E> subList(int fromIndex,
                       int toIndex)
Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations.
This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a list can be used as a range operation by passing a subList view instead of a whole list. For example, the following idiom removes a range of elements from a list:

      list.subList(from, to).clear();
 
Similar idioms may be constructed for indexOf(Object) and lastIndexOf(Object), and all of the algorithms in the Collections class can be applied to a subList.
The semantics of the list returned by this method become undefined if the backing list (i.e., this list) is structurally modified in any way other than via the returned list. (Structural modifications are those that change the size of this list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.)

Specified by:
	subList in interface List<E>
Overrides:
	subList in class AbstractList<E>
Parameters:
	fromIndex - low endpoint (inclusive) of the subList
	toIndex - high endpoint (exclusive) of the subList
Returns:
	a view of the specified range within this list
Throws:
	IndexOutOfBoundsException - if an endpoint index value is out of range (fromIndex < 0 || toIndex > size)
	IllegalArgumentException - if the endpoint indices are out of order (fromIndex > toIndex)

猜你喜欢

转载自blog.csdn.net/zhangpeterx/article/details/88716563