class SwapTest{
public static void swap(String[] temp){
String min=temp[0];
String max=temp[0];
for(int i=0;i<temp.length;i++){
if(min.compareTo(temp[i])>0){
min=temp[i];
}
if(max.compareTo(temp[i])<0){
max=temp[i];
}
}
swapFirst(max,temp);
swapLast(min,temp);
}
public static void swapFirst(String t,String[] temp){
String data=t;
t=temp[0];
temp[0]=data;
}
public static void swapLast(String t,String[] temp){
String data=t;
t=temp[temp.length-1];
temp[temp.length-1]=data;
}
}
public class Swap {
public static void main(String[] args) {
String[] data=new String[]{"a","b","d","c"};
SwapTest.swap(data);
for(int x=0;x<data.length;x++){
System.out.println(data[x]);
}
}
}
这是最初写出来的版本,输出结果为dbda。结果不对,少了c。正确的结果应该data[2]=c,之后就思考为什么错误。经过思考之后,发现是因为data[2]的值从头到尾就没变过。在swap方法中,min和max的值在循环之后就被赋予了最小元素的值和最大元素的值。之后再进行swapFirst方法,是把max和data[0]做了交换。而max只是元素的值,在本例中,max=data[2]。max只是data[2]的值d。所以,swapFirst方法实现的是把最大值赋予给了data[0],data[0]的值赋予给了max。所以这个时候max的值就等于data[0]即a了。换句话说,就是把第一个元素的值替换成了最大元素的值,而最大元素data[2]根本就没变,变的是max。swapLast方法同理。经过思考之后,做出如下改动:
class SwapTest{
public static void swap(String[] temp){
String min=temp[0];
String max=temp[0];
for(int i=0;i<temp.length;i++){
if(min.compareTo(temp[i])>0){
min=temp[i];
}
if(max.compareTo(temp[i])<0){
max=temp[i];
}
}
swapFirst(max,temp);
swapLast(min,temp);
}
public static void swapFirst(String t,String[] temp){
for(int i=0;i<temp.length;i++){
if(temp[i]==t){
String data=temp[i];
temp[i]=temp[0];
temp[0]=data;
}
}
}
public static void swapLast(String t,String[] temp){
for(int i=0;i<temp.length;i++){
if(temp[i]==t){
String data=temp[i];
temp[i]=temp[temp.length-1];
temp[temp.length-1]=data;
}
}
}
}
public class Swap {
public static void main(String[] args) {
String[] data=new String[]{"a","b","c","d"};
SwapTest.swap(data);
for(int x=0;x<data.length;x++){
System.out.println(data[x]);
}
}
}
此时就没有错误了!题目的要求是写一个数组,没说数组的类型。刚刚复习了下Java核心技术的泛型部分,于是打算用采用泛型再写一次。
class SwapTest{
public static <T extends Comparable<T>>void swap(T[] temp){
T min=temp[0];
T max=temp[0];
for(int i=0;i<temp.length;i++){
if(min.compareTo(temp[i])>0){
min=temp[i];
}
if(max.compareTo(temp[i])<0){
max=temp[i];
}
}
swapFirst(max,temp);
swapLast(min,temp);
}
public static <T>void swapFirst(T t,T[] temp){
for(int i=0;i<temp.length;i++){
if(temp[i]==t){
T data=temp[i];
temp[i]=temp[0];
temp[0]=data;
}
}
}
public static <T>void swapLast(T t,T[] temp){
for(int i=0;i<temp.length;i++){
if(temp[i]==t){
T data=temp[i];
temp[i]=temp[temp.length-1];
temp[temp.length-1]=data;
}
}
}
}
public class Swap {
public static void main(String[] args) {
Integer[] data=new Integer[]{1,2,3,6,3,10,70,4,9};
SwapTest.swap(data);
for(int x=0;x<data.length;x++){
System.out.println(data[x]);
}
}
}
这里出现了一个问题。最开始的时候main方法中数组实例化的时候采用了int,导致SwapTest.swap(data)报错,于是才发现泛型方法里面参数不能用基础类型,于是改成了Integer。
至此,一个简单的问题,就被我如此复杂地写完了
