Java静态内部类的实际应用

来源:互联网 发布:乐乎lofte网页版 编辑:程序博客网 时间:2024/05/19 22:07

Java静态内部类在实际中的典型应用:

有时候,使用内部类只是为了把一个类隐藏在另一个类的内部,该内部类并不需要引用外部类对象。

例子:

考虑一下计算一个数组中最大值和最小值的问题,当然,可以编写两个方法,一个计算最大值,一个计算最小值,在调用这两个方法的时候,数组被遍历两次,

而如果数组只被遍历一次就可以计算出最大值和最小值,那么效率就大大提高了。

通过一个方法就计算出最大值和最小值:这个方法需要返回两个数(max 和 min),为此可以定义一个类来封装这种数据结构,这个类只是起数据封装的作用,可以将其定义为静态内部类。

public class Test{    //Pair类,起数据封装的作用    public static class Pair{        private double first;        private double second;        public Pair(double f, double s){            Pair.this.first = f;            Pair.this.second = s;        }        public double getFirst(){            return Pair.this.first;        }        public double getSecond(){            return Pair.this.second;        }    }    public Pair maxmin(double[] array){        double min = Double.MAX_VALUE;        double max = Double.MIN_VALUE;        for(double x : array){            if(x<min){                min = x;            }            if(x>max){                max = x;            }        }        return new Pair(max,min);    }    public static void main(String[] args){        Test te = new Test();        double[] teArgs = new double[]{2.13,100.0,11.2,34.5,67.1,88.9};        Pair res = te.maxmin(teArgs);        System.out.println("max = "+res.getFirst());        System.out.println("min = "+res.getSecond());    }}




0 0