那里。
我一直在从Core Java第1卷第9版学习Java,我对书中的一个示例(清单6.8)感到有点困惑。
为什么在类'ArrayAlg‘的方法名(minmax)前有一个'Pair’?
public static Pair minmax(double[] values)源码如下:
package staticInnerClass;
public class StaticInnerClassTest
{
public static void main(String[] args)
{
double[] d = new double[20];
for (int i = 0; i < d.length; i++)
d[i] = 100 * Math.random();
ArrayAlg.Pair p = ArrayAlg.minmax(d);
System.out.println("min = " + p.getFirst());
System.out.println("max = " + p.getSecond());
}
}
class ArrayAlg
{
/**
* A pair of floating-point numbers
*/
public static class Pair
{
private double first;
private double second;
/**
* Constructs a pair from two floating-point numbers
* @param f the first number
* @param s the second number
*/
public Pair(double f, double s)
{
first = f;
second = s;
}
/**
* Returns the first number of the pair
* @return the first number
*/
public double getFirst()
{
return first;
}
/**
* Returns the second number of the pair
* @return the sceond number
*/
public double getSecond()
{
return second;
}
}
/**
* Computes both the minimum and the maximum of an array
* @param values an array of floating-point numbers
* @return a pair whose first element is the minimum and whose second element is the maximum
*/
public static Pair minmax(double[] values)
{
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
for (double v : values)
{
if (min > v)
min = v;
if (max < v)
max = v;
}
return new Pair(min, max);
}
}发布于 2015-10-07 15:45:59
声明public static Pair minmax(double[] values)中的Pair是该方法的返回类型。Pair是一个内部类的事实是无关紧要的,如果它是一个顶级类,则声明看起来将完全相同(当然,假设您导入了该类)。
发布于 2015-10-07 15:50:41
Pair是ArrayAlg的一个静态内部类-有多种方法可以声明Pair类型的变量,但最常见的方法如下所示:
[outer class].[inner class] [variable name] = ...这就好像外部类只是完整路径中的另一个级别,它将包括包,到您感兴趣的类(类型)。
虽然可以说编译器可以从方法返回类型推断出变量类型,但这不是Java的工作方式,因此您必须明确。
https://stackoverflow.com/questions/32986461
复制相似问题