日期:2014-05-20 浏览次数:21025 次
package com.yaxing.suanfa; public class ArrayDemo { /** * 改变了数组 * */ public static int[] reverseArray(int[] a){ int temp; for(int i=0;i<a.length/2;i++){ temp = a[i]; a[i] = a[a.length-1-i]; a[a.length-1-i] = temp; } return a; } public static char[] reverseArray(char[] a){ char temp; for(int i=0;i<a.length/2;i++){ temp = a[i]; a[i] = a[a.length-1-i]; a[a.length-1-i] = temp; } return a; } /** * 使用泛型 * */ public Object[] reverseArray1(Object[] a){ Object temp; for(int i=0;i<a.length/2;i++){ temp = a[i]; a[i] = a[a.length-1-i]; a[a.length-1-i] = temp; } return a; } /** * 逆序输出,不逆转数组 * */ public static int[] reverseArrayPrint(int[] a){ for(int i=0;i<a.length;i++){ if(i==a[a.length-1]){ System.out.print(a[a.length-1-i]+" "); }else{ System.out.print(a[a.length-1-i]+"、"); } } return a; } /** * @param args */ public static void main(String[] args) { int a[] = new int[100]; for(int i=0;i<a.length;i++){ a[i]=i; } System.out.println("原始数组:"); for(int i:a){ if(i==a[a.length-1]){ System.out.print(i+" "); }else{ System.out.print(i+"、"); } } System.out.println(); int b[] = ArrayDemo.reverseArray(a); System.out.println("逆转后数组:"); for(int i:b){ if(i==b[b.length-1]){ System.out.print(i+" "); }else{ System.out.print(i+"、"); } } System.out.println(); System.out.println("只逆序打印数组"); ArrayDemo.reverseArrayPrint(a); String cc = "abcdefg"; char c[] = cc.toCharArray();; ArrayDemo.reverseArray(c); System.out.println(); System.out.println("逆序字符串"); for(char i:c){ if(i==c[c.length-1]){ System.out.print(i+" "); }else{ System.out.print(i+"、"); } } } }