Skip to content

Instantly share code, notes, and snippets.

@strongant
Last active September 17, 2017 03:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save strongant/7e2baab6291a569586bab1b97b0b22c6 to your computer and use it in GitHub Desktop.
Save strongant/7e2baab6291a569586bab1b97b0b22c6 to your computer and use it in GitHub Desktop.
Java中数组和集合进行反转
package com.strongant.algorithm;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 集合反转
*
* @author <a href="mailto:strongant1994@gmail.com">strongant</a>
* @see
* @since 2017/8/20
*/
public class ListReverse {
public static void main(String[] args) {
int[] arr = new int[]{
10, 9, 8, 7, 6, 5, 4, 3, 2, 1
};
List list = new ArrayList();
list.add(3);
list.add(2);
list.add(1);
//其中jdk中自带的reverse方法内部实现使用了右移操作相关判断,比较注意的是List的set方法
//该方法结构如下: E set(int index, E element) 在指定的集合索引插入某元素,然后返回该索引原始值
//参考AbstractSequentialList.java 中的 set(int index, E element) 方法可知
Collections.reverse(list);
System.out.println(list);
reverseArray(arr);
for (int i : arr) {
System.out.print(i);
System.out.print("\t");
}
}
private static void reverseArray(int[] arr) {
for (int i = 0, len = arr.length - 1, half = arr.length >> 1; i < half; i++) {
int temp = arr[len - i];
arr[len - i] = arr[i];
arr[i] = temp;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment