简体   繁体   English

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

[英]What do the Type Parameter Names P and R mean and how are they used?

I recently posted a question on SO ( How do I use double dispatch to analyze intersection of graphic primitives? ) in which one of the answers (which I have accepted) used generics including <P> and <R> . 我最近在SO上发布了一个问题( 如何使用双调度来分析图形基元的交集? ),其中一个答案(我已经接受)使用了泛型,包括<P><R> They aren't in the Oracle docs Java generics list but I have seen them used elsewhere (eg Generics overkill in visitor pattern ) - are they specific to the visitor pattern? 它们不在Oracle docs Java泛型列表中,但我已经在其他地方看到过它们(例如,访问者模式中的泛型过大 )-它们是否特定于访问者模式? And why are both super and extends used? 为何同时使用superextends

The code is: 代码是:

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...
        }
    };
}

and I'd be grateful for 我会很感激

The names P and R are just identifiers. 名称PR只是标识符。 Judging by how they're used, I think they mean "Parameter" and "Return Value", respectively. 从使用方式来看,我认为它们分别表示“参数”和“返回值”。

Now, in the Shape.accept method, parameters can be made to be contra-variant, that's why you see super with P , and a return value co-variant, and that's why you see extends with R there. 现在,在Shape.accept方法中,可以将参数设为反变量,这就是为什么您看到Psuper以及返回值协变量的原因,这就是为什么在那里看到R extends的原因。

When you create a class: 创建课程时:

public class MyComparable<R>{

    public boolean compare(R r1, R r2){
        // Implementation
    }
}

you are just indicating that you need to use two objects of the same Class. 您只是表示需要使用同一类的两个对象。

to initialize that class you would use 初始化您将使用的类

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

so you are only specifying the kind of relation that the objects of this class will have. 因此,您仅指定此类对象将具有的关系类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM