我正在尝试制作一个比较器,我可以用它来按自然顺序对字符串进行排序。我希望比较器是通用的,这样我就可以通过它传递来自任何类的字符串。
例如,我有一个类// CHECK TO SEE IF WE FOUND A MATCH
if (isset($matches[1])) {
// GO AHEAD AND DO THE MATCH ON THE SPANS
preg_match_all('~<span class="my-tag">(.*?)</span>~s', $string, $span_matches);
$count = count($span_matches[1]);
// IF WE FOUND MULTIPLE MATCHES, LIST THEM OUT
if ($count > 1) {
print 'COUNT IS: '.$count;
print_r($span_matches[1]);
}
// WE DID NOT MATCH ANY SPAN TAGS
elseif ($count == 0) {
print 'COUNT IS ZERO - CRAP';
}
// IF WE ONLY FOUND ONE MATCH, WE DON'T NEED TO DO ANYTHING
else {
print 'COUNT IS EXACTLY 1 - DO NOTHING';
}
}
// WE DID NOT FIND AN INITAL MATCH TO BEGIN WITH
else {
print 'WE DID NOT FIND A MATCH';
}
,它实现了可比性,Name
字符串的自然顺序是字符串的长度。但是,在某些情况下,我希望Name
字符串按其自然顺序排序。为此,我在下面写一个比较器。
Name
我用该代码得到的错误是它告诉我T无法解析为某种类型。我认为问题出在我从import java.util.Comparator;
public class AlphabeticalOrderComparator implements Comparator<T> {
public int compare(T obj1, T obj2) {
Name name1 = (Name)obj1;
Name name2 = (Name)obj2;
return name1.name.compareTo(name2.name);
}
到T
的类型转换。
有人能告诉我如何解决这个错误吗?
答案 0 :(得分:5)
T
。你需要写
class AlphabeticalOrderComparator<T> implements Comparator<T>
但即便如此也没有意义。应该是什么
class AlphabeticalComparator implements Comparator<Name>
...因为Comparator
仅适用于Name
。