How to handle comparison operator for Generic Java class accepting String or Integer(如何处理接受字符串或整数的通用 Java 类的比较运算符)
问题描述
我有兴趣使用可以处理 String
或 Integer
数据类型的通用 Java 类.我想使用比较运算符,但它似乎有一个编译错误:
I am interested in using a generic Java class which can handle String
or Integer
data type. I'd like to utilize the comparison operator, but it appears to have a compile error:
运算符 <不能用于通用 T
Operator < cannot be used on generic
T
对于T
,如何使用比较运算符(如<、>、= 等)?(假设 T
是 Number
或 String
).
How can I achieve using comparison operators such as <, >, =, etc. for T
? (Assuming T
is Number
or String
).
public class Node<T> {
public T value;
public Node(){
}
public void testCompare(T anotherValue) {
if(value == anotherValue)
System.out.println("equal");
else if(value < anotherValue)
System.out.println("less");
else if(value > anotherValue)
System.out.println("greater");
}
}
}
推荐答案
使用可比
界面:
public class Node<T extends Comparable<T>> {
public T value;
public Node() {
}
public void testCompare(T anotherValue) {
int cmp = value.compareTo(anotherValue);
if (cmp == 0)
System.out.println("equal");
else if (cmp < 0)
System.out.println("less");
else if (cmp > 0)
System.out.println("greater");
}
}
由String
、Integer
、Long
、Double
、Date
实现和许多其他课程.
It's implemented by String
, Integer
, Long
, Double
, Date
and many other classes.
这篇关于如何处理接受字符串或整数的通用 Java 类的比较运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何处理接受字符串或整数的通用 Java 类的比较运算符


基础教程推荐
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01