Java Long Compare and ValueOf method undefined

佐手、 提交于 2019-12-20 04:26:09

问题


I am referencing my java version JDK 1.8 but I am still getting error. What is wrong with this referencing (writing Java after 6 years)? or any other simpler way to do this? I did some search and these functions are available in later java versions. Eclipse is Oxygen

The method valueOf(Long) is undefined for the type Long

The method compareTo() is undefined for the type Long

import java.util.Comparator;
import java.lang.Long;

public class MyComparator<Long> implements Comparator<Long>{
    @Override
    public int compare(Long long1, Long long2) {    
        //Long.compareTo()
          return Long.valueOf(long1).compareTo(Long.valueOf(long2));
    }
}

and JDK points to

/Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home


回答1:


Your declaration of MyComparator declares a generic type of name Long, and that then shadows java.lang.Long. Your class shouldn't be generic. Also, you don't need Long.valueOf since you already have Long instance. Change it to remove the generic, like

public class MyComparator implements Comparator<Long> {
    @Override
    public int compare(Long long1, Long long2) {
        return long1.compareTo(long2);
    }
}



回答2:


Alternatively anytime you need Comparator<Long> or any other class that implements Comparable you can call:

Comparator.naturalOrder()

https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#naturalOrder--



来源:https://stackoverflow.com/questions/46270157/java-long-compare-and-valueof-method-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!