文章标题

来源:互联网 发布:ios版nba2k17捏脸数据 编辑:程序博客网 时间:2024/06/07 22:16

/**
*静态的应用
*
*每个应用程序中都有共性的功能
*可以讲这些功能进行抽取 独立封装 以便服用
*虽然可以通过建立Arraytool的对象使用这些工具方法 对数组进行操作
*发现了问题
*1,对象是用于封装数据的 可是ArrayTool对象并未封装特有数据 根本用不到对象
*2,操作数组的每一个方法都没有用到ArrayTool对象中的特有数据
*
*这时就考虑 让程序更严谨 是不需要对象的。
*可以将Arraytool中的方法都定义成静态static的,直接通过类名调用即可
*
*将方法都静态后,可以便于使用 但该类还是可以被其他程序建立对象的。
*为了更为严谨 强制让该类不能建立对象
*可以将通过构造函数私有化完成
* */
public class Demo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

    int[] arr  = {2,4,5,4,3,9};    int max = getMax(arr);    System.out.println("max="+max);}

public static int getMax(int[] arr)
{

     int max = 0;    for(int x=1;x<arr.length;x++ )    {        if(arr[x]>arr[max])            max=x;    }    return arr[max];}

}
class Test{

public static int getMax(int[] arr)   {         int max = 0;        for(int x=1;x<arr.length;x++ )        {            if(arr[x]>arr[max])                max=x;        }        return arr[max];    }

}
class ArrayTool{

private ArrayTool(){}//私有化 强制不可以创建对象public static int getMax(int[] arr)   {         int max = 0;        for(int x=1;x<arr.length;x++ )        {            if(arr[x]>arr[max])                max=x;        }        return arr[max];    }public static int getMin(int[] arr)   {        int min = 0;        for(int x=1;x<arr.length;x++ )        {            if(arr[x]<arr[min])                min=x;        }        return arr[min];    }public static void selectSort(int[] arr){    for(int x=0;x<arr.length-1;x++)    {      for(int y=x+1;y<arr.length;y++)      {          if(arr[x]>arr[y])          {              swap(arr,x,y);          }      }    }}public static void bubbleSort(int[] arr){      for(int x=0;x<arr.length-1;x++)      {          for(int y=x+1;y<arr.length;y++)          {              if(arr[x]>arr[y])              {                  swap(arr,x,y);              }          }      }}public static void swap(int[] arr, int a, int b) {    // TODO Auto-generated method stub    int temp = arr[a];    arr[a] = arr[b];    arr[b]=temp;}

}

class ArrayToolDemo{

public static void main(String[] args){    int[] arr = {2,3,4,5,2,1,8};    //ArrayTool tool = new ArrayTool();    //int max = tool.getMax(arr);    //int min = tool.getMin(arr);    //System.out.println("MAX = "+max);    //System.out.println("MIN = "+min);    int max = ArrayTool.getMax(arr);    System.out.println("MAX = "+max);}

}

0 0
原创粉丝点击