جافا: مشكلة بسيطة مع واجهات والأجنبي
-
11-09-2019 - |
سؤال
لقد قمت بواجهة للعمل مع JGrapht. الاستخدام المقصود الخاص بي هو مثل Comparable
, ، في تلك التنفيذ Comparable
يسمح بالكائنات المراد استخدامها مع بعض هياكل البيانات. smasiarly، لدي وظيفة JGrapht التي أرغب في العمل مع أي شيء Distanceable
.
public interface Distanceable<E> {
/**
* A representation of the distance between these two objects.
* If the distance between a0 and a1 is undefined, <code>a0.hasEdge(a1)</code> should return false;
* @param o
* @return
*/
public int distance(E o);
/**
* Are these two objects connected?
* @param o
* @return True if the two objects are connected in some way, false if their distance is undefined
*/
public boolean hasEdge(E o);
}
هنا هي وظيفة JGrapht الخاصة بي في JGraphtities. انها غير محددة ل Animal
, ، ولكن بالنسبة ل Distanceable
:
public static <E extends Distanceable> WeightedGraph<E, DefaultWeightedEdge> graphOfDistances(Set<E> nodes) {
WeightedGraph<E, DefaultWeightedEdge> g = new SimpleWeightedGraph<E, DefaultWeightedEdge>(DefaultWeightedEdge.class);
for (E a : nodes) {
g.addVertex(a);
}
for (E a : nodes) {
for (E a1 : nodes) {
if (a.hasEdge(a1)) {
g.addEdge(a, a1);
g.setEdgeWeight(g.getEdge(a, a1), a.distance(a1));
}
}
}
return g;
}
لكنه لا يعمل. ينتج المحول البرمجي خطأ على هذا السطر في فئة أخرى يدعو هذه الطريقة:
WeightedGraph<Animal, DefaultWeightedEdge> graphOfAnimals = JGraphtUtilities.graphOfAnimals(zoo);
الخطأ هو:
The method graphOfAnimals(Set<Animal>) is undefined for the type JGraphtUtilities
ومع ذلك،
public class Animal implements Distanceable<Animal> {
ماذا أفعل الخطأ هنا؟
مشكلة أخرى: المترجم يعطي هذا التحذير:
Distanceable is a raw type. References to generic type Distanceable<E> should be parameterized.
ما النوع الذي أريد أن أقدمه، إذا أردت أن تعمل هذه الوظيفة مع كل شيء Distanceable
أشياء؟
المحلول
طريقة
graphOfAnimals(Set<Animal>)
غير محدد لنوع الصف
الطريقة التي تعرضها في نموذج التعليمات البرمجية الخاص بك هي graphOfDistances
وبعد المشكلة هي مع الطريقة graphOfAnimals
. وبعد وبالتالي...
هل لديك graphOfAnimals
الطريقة التي تأخذ Set<Animal>
في ال JGraphtUtilities
صف دراسي؟