栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在main方法内编写函数-Java

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在main方法内编写函数-Java

当Java 8发布时,Closure /
Lambda功能应该可以实现,以便您可以在main方法中定义max方法。在此之前,您只能在特殊情况下在main方法中定义一个方法。

碰巧的是,您的问题确实属于特殊情况。有一个接口(可比较),其中包含比较两个相同类型的事物的逻辑。结果,该代码可以如下重写:

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);  }}

这仅起作用,因为标准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);  }}

我怀疑您的问题更多是关于Java语言的功能,而不是与订购数字(及其他事物)有关的标准实践。因此,这可能没有用,但我想以防万一。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/392239.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号