首页 > 编程知识 正文

数组倒序三种类型,数组颠倒顺序

时间:2023-05-05 13:41:30 阅读:243006 作者:1226

直接数组元素对换
@Test
public void testReverseSelf() throws Exception {
System.out.println(“use ReverseSelf”);

String[] strings = { "ramer", "jelly", "bean", "cake" };System.out.println("t" + Arrays.toString(strings));for (int start = 0, end = strings.length - 1; start < end; start++, end--) { String temp = strings[end]; strings[end] = strings[start]; strings[start] = temp;}System.out.println("t" + Arrays.toString(strings));

}

使用ArrayList: ArrayList存入和取出的顺序是一样的,可以利用这里特性暂时存储数组元素.
@Test
public void testArrayList() throws Exception {
System.out.println(“use ArrayList method”);

String[] strings = { "ramer", "jelly", "bean", "cake" };System.out.println("t" + Arrays.toString(strings));List<String> list = new ArrayList<>(strings.length);for (int i = strings.length - 1; i >= 0; i--) { list.add(strings[i]);}strings = list.toArray(strings);System.out.println("t" + Arrays.toString(strings));

}

使用Collections和Arrays工具类
@Test
public void testCollectionsReverse() throws Exception {
System.out.println(“use Collections.reverse() method”);

String[] strings = { "ramer", "jelly", "bean", "cake" };System.out.println("t" + Arrays.toString(strings));// 这种方式仅针对引用类型,对于基本类型如:// char[] cs = {'a','b','c','g','d'};// 应该定义或转换成对应的引用类型: // Character[] cs = {'a','b','c','g','d'};Collections.reverse(Arrays.asList(strings));System.out.println("t" + Arrays.toString(strings)); }

作者:Ramer-F
来源:CSDN
原文:https://blog.csdn.net/u011699931/article/details/52554787

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。