use*_*119 8 java methods program-entry-point function
你能在main方法中写一个方法吗?例如,我找到了这段代码:
public class TestMax {
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
System.out.println("The maximum between is " + k);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
方法max可以在main方法中编码吗?
当Java 8出来时,Closure/Lambda功能应该使它能够在main方法中定义max方法.在此之前,您只能在特殊情况下在main方法中定义方法.
碰巧,你的问题确实属于特殊情况.有一个接口(Comparable),它封装了比较两个相同类型的东西的逻辑.因此,代码可以重写如下:
public class TestMax {
public static void main(String[] args) {
int i = 5;
int j = 2;
Comparator<Integer> compare = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// Because Integer already implements the method Comparable,
// This could be changed to "return o1.compareTo(o2);"
return o1 - o2;
}
};
// Note that this will autobox your ints to Integers.
int k = compare.compare(i, j) > 0 ? i : j;
System.out.println("The maximum between is " + k);
}
}
Run Code Online (Sandbox Code Playgroud)
这只能起作用,因为比较器接口已存在于标准Java发行版中.通过使用库可以使代码更好.如果我正在编写此代码,我会将Google Guava添加到我的类路径中.然后我可以写下面的内容:
public class TestMax {
public static void main(String[] args) {
int i = 5;
int j = 2;
// The 'natural' ordering means use the compareTo method that is defined on Integer.
int k = Ordering.<Integer>natural().max(i, j);
System.out.println("The maximum between is " + k);
}
}
Run Code Online (Sandbox Code Playgroud)
我怀疑你的问题更多的是关于Java语言的能力,而不是与订购号码(和其他东西)有关的标准做法.所以这可能没有用,但我想我会分享以防万一.
| 归档时间: |
|
| 查看次数: |
56360 次 |
| 最近记录: |