[英]How to translate this piece of C# generics to Java
鑒於以下 C# 代碼,我如何將其轉換為 Java?
public class Stop : IComparable<Stop>
{
public int CompareTo(Stop other) { ... }
}
public class Sequence<T> : IEnumerable<T>
where T : IComparable<T>
{
public IEnumerator<T> GetEnumerator() { ... }
IEnumerator IEnumerable.GetEnumerator() { ... }
}
public class Line<T> : Sequence<T>, IComparable<Line<T>>
where T : Stop
{
public int CompareTo(Line<T> other) { ... }
}
我很難將 class 線的定義翻譯成 Java。 我的第一次嘗試如下:
public class Line<T extends Stop> extends Sequence<T> implements Comparable<Line<T>> { ... }
但是,編譯器為extends Sequence<T>
報告以下錯誤:
Error: type argument T is not within bounds of type-variable T
將定義更改為
public class Line<T extends Comparable<T>> extends Sequence<T> implements Comparable<Line<T>> { ... }
修復了錯誤,但沒有准確反映意圖:我想強制所有與 Line 一起使用的 arguments 類型必須是 Stop 的子類型。 使用T extends Comparable<T>
將允許實現接口的任意類型。
我不明白錯誤的原因。 有沒有辦法在不改變類型結構的情況下表達這種關系,或者這是 Java 的 generics 的限制?
編輯:訪問https://www.onlinegdb.com/S1u9wclnH以查看我嘗試的精簡版本。
問題是您對class Sequence
的定義。
public class Sequence<T> : IEnumerable<T>
where T : IComparable<T> { ... }
This C# class makes use of the fact that IComparable
is contra-variant, so the C# class doesn't require exactly T: IComparable<T>
, but is also happy if T
is comparable with one of its base classes. 因此,即使T
使用派生自Stop
的 class 實例化,該代碼也可以工作。
Java 沒有聲明地點差異,但使用地點差異(通配符)。 您的 Java Sequence
class 無法為派生自Stop
的類實例化,但您的Line
class 可能是。 因此編譯器錯誤。
要解決此問題,每當您在界限內使用Comparable
時,都需要將 C# 的聲明站點差異轉換為 Java 的通配符:
class Sequence<T extends Comparable<? super T>> implements Iterable<T> { ... }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.