(1)声明一个数组工具类ArraysTools,包含几个重载方法
-
重载方法系列1:可以为int[],double[],char[]数组实现从小到大排序
-
void sort(int[] arr)
-
void sort(double[] arr)
-
void sort(char[] arr)
-
-
重载方法系列2:toString方法,可以遍历int[],double[],char[]数组,遍历结果形式:[元素1,元素2,。。。]
-
String toString(int[] arr)
-
String toString(double[] arr)
-
String toString(char[] arr)
-
(2)在测试类的
package com.atguigu.overload;
public class ArraysTools {
void sort(int[] arr){
for (int i = 1; i < arr.length; i++) {
for (int j = 0; j < arr.length- i ; j++) {
if(arr[j] > arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
void sort(double[] arr){
for (int i = 1; i < arr.length; i++) {
for (int j = 0; j < arr.length- i ; j++) {
if(arr[j] > arr[j+1]){
double temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
void sort(char[] arr){
for (int i = 1; i < arr.length; i++) {
for (int j = 0; j < arr.length- i ; j++) {
if(arr[j] > arr[j+1]){
char temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
String toString(int[] arr){
String result = "[";
for (int i = 0; i < arr.length; i++) {
if(i<arr.length-1){
result += arr[i] + ",";
}else{
result += arr[i] + "]";
}
}
return result;
}
String toString(double[] arr){
String result = "[";
for (int i = 0; i < arr.length; i++) {
if(i<arr.length-1){
result += arr[i] + ",";
}else{
result += arr[i] + "]";
}
}
return result;
}
String toString(char[] arr){
String result = "[";
for (int i = 0; i < arr.length; i++) {
if(i<arr.length-1){
result += arr[i] + ",";
}else{
result += arr[i] + "]";
}
}
return result;
}
}
main方法中调用
package com.atguigu.overload;
public class ArraysToolsTest {
public static void main(String[] args) {
ArraysTools tools = new ArraysTools();
int[] arr1 = {5,4,2,17,3};
tools.sort(arr1);
System.out.println(tools.toString(arr1));
double[] arr2 = {5.0 ,4.0, 2.0,17.0,3.0};
tools.sort(arr2);
System.out.println(tools.toString(arr2));
char[] arr3 = {'h','a','o','b','t'};
tools.sort(arr3);
System.out.println(tools.toString(arr3));
}
}