如何处理接受String或Integer的通用Java类的比较运算符 [英] How to handle comparison operator for Generic Java class accepting String or Integer
本文介绍了如何处理接受String或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
如何为 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.
这篇关于如何处理接受String或Integer的通用Java类的比较运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文