代码之家  ›  专栏  ›  技术社区  ›  peter.murray.rust

类型参数名称P和R是什么意思?它们是如何使用的?

  •  2
  • peter.murray.rust  · 技术社区  · 11 年前

    我最近在SO上发布了一个问题( How do I use double dispatch to analyze intersection of graphic primitives? )其中一个答案(我已经接受)使用了泛型,包括 <P> <R> 。它们不在Oracle文档中 Java generics list 但我在其他地方看到过它们的使用(例如。 Generics overkill in visitor pattern )-它们是特定于访客模式的吗?为什么两者都是 super extends 习惯于

    代码为:

    public interface ShapeVisitor<P, R> { 
        R visitRect(Rect rect, P param);
        R visitLine(Line line, P param);
        R visitText(Text text, P param);
    }
    
    public interface Shape {
        <P, R> R accept(P param, ShapeVisitor<? super P, ? extends R> visitor);
        Shape intersectionWith(Shape shape);
    }
    
    public class Rect implements Shape {
    
        public <P, R> R accept(P param, ShapeVisitor<? super P, ? extends R> visitor) {
            return visitor.visitRect(this, param);
        }
    
        public Shape intersectionWith(Shape shape) {
            return shape.accept(this, RectIntersection);
        }
    
        public static ShapeVisitor<Rect, Shape> RectIntersection = new ShapeVisitor<Rect, Shape>() {
            public Shape visitRect(Rect otherShape, Rect thisShape) {
                // TODO...
            }
            public Shape visitLine(Line otherShape, Rect thisShape) {
                // TODO...
            }
            public Shape visitText(Text otherShape, Rect thisShape) {
                // TODO...
            }
        };
    }
    

    我会很感激

    2 回复  |  直到 7 年前
        1
  •  3
  •   Jordão    11 年前

    名字 P R 只是标识符。从它们的使用方式来看,我认为它们分别是指“参数”和“返回值”。

    现在,在 Shape.accept 方法,可以使参数为反变量,这就是为什么您看到 super 具有 P ,和一个返回值协变,这就是为什么你会看到 extends 具有 R 那里

        2
  •  0
  •   RamonBoza    11 年前

    创建类时:

    public class MyComparable<R>{
    
        public boolean compare(R r1, R r2){
            // Implementation
        }
    }
    

    您只是表示需要使用同一类的两个对象。

    要初始化要使用的类

    List<String> strings = fillStrings();
    int i = 1;
    while(i < strings.size()){
        boolean comparePreviousWithThis = new MyComparable<String>().compare(strings.get(i-1),strings.get(i));
    }
    

    因此,您只指定此类对象将具有的关系类型。