我有一个大小为300000的数组,我希望它将它分成两个相等的部分。有没有什么方法可以用来实现这个目标?
它会比for-loop操作更快还是会对性能没有影响?
答案 0 :(得分:57)
您可以使用System.arraycopy()
。
int[] source = new int[1000];
int[] part1 = new int[500];
int[] part2 = new int[500];
// (src , src-offset , dest , offset, count)
System.arraycopy(source, 0 , part1, 0 , part1.length);
System.arraycopy(source, part1.length, part2, 0 , part2.length);
答案 1 :(得分:51)
这可以实现您的目的,而无需在返回新数组时创建新数组。
int[] original = new int[300000];
int[] firstHalf = Arrays.copyOfRange(original, 0, original.length/2);
答案 2 :(得分:8)
在具有固定最大大小的多个数组中拆分数组。
public static <T extends Object> List<T[]> splitArray(T[] array, int max){
int x = array.length / max;
int r = (array.length % max); // remainder
int lower = 0;
int upper = 0;
List<T[]> list = new ArrayList<T[]>();
int i=0;
for(i=0; i<x; i++){
upper += max;
list.add(Arrays.copyOfRange(array, lower, upper));
lower = upper;
}
if(r > 0){
list.add(Arrays.copyOfRange(array, lower, (lower + r)));
}
return list;
}
示例 - 11的数组应分成多个不超过5的数组:
// create and populate an array
Integer[] arr = new Integer[11];
for(int i=0; i<arr.length; i++){
arr[i] = i;
}
// split into pieces with a max. size of 5
List<Integer[]> list = ArrayUtil.splitArray(arr, 5);
// check
for(int i=0; i<list.size(); i++){
System.out.println("Array " + i);
for(int j=0; j<list.get(i).length; j++){
System.out.println(" " + list.get(i)[j]);
}
}
输出:
Array 0
0
1
2
3
4
Array 1
5
6
7
8
9
Array 2
10
答案 3 :(得分:1)
答案 4 :(得分:0)
使用此代码,它可以完美地用于奇数或甚至列表大小。希望它对某人有所帮助。
int listSize = listOfArtist.size();
int mid = 0;
if (listSize % 2 == 0) {
mid = listSize / 2;
Log.e("Parting", "You entered an even number. mid " + mid
+ " size is " + listSize);
} else {
mid = (listSize + 1) / 2;
Log.e("Parting", "You entered an odd number. mid " + mid
+ " size is " + listSize);
}
//sublist returns List convert it into arraylist * very important
leftArray = new ArrayList<ArtistModel>(listOfArtist.subList(0, mid));
rightArray = new ArrayList<ArtistModel>(listOfArtist.subList(mid,
listSize));