Java 类型参数名称P和R的含义是什么?它们是如何使用的?
我最近在SO()上发布了一个问题,其中一个答案(我已经接受)使用了泛型,包括Java 类型参数名称P和R的含义是什么?它们是如何使用的?,java,generics,Java,Generics,我最近在SO()上发布了一个问题,其中一个答案(我已经接受)使用了泛型,包括和。它们不在Oracle文档中,但我在其他地方见过它们(例如),它们是否特定于访问者模式?为什么同时使用super和extends 代码是: public interface ShapeVisitor<P, R> { R visitRect(Rect rect, P param); R visitLine(Line line, P param); R visitText(Text t
和
。它们不在Oracle文档中,但我在其他地方见过它们(例如),它们是否特定于访问者模式?为什么同时使用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...
}
};
}
公共接口ShapeVisitor{
R visitRect(Rect Rect,P param);
R visitLine(Line-Line,P参数);
R visitText(文本,P参数);
}
公共界面形状{
R accept(P param,ShapeVisitor名称
P
和R
只是标识符。从它们的使用方式来看,我认为它们分别表示“参数”和“返回值”
现在,在Shape.accept
方法中,可以将参数设置为反变量,这就是为什么您会看到super
带有p
,以及返回值的协变量,这就是为什么您会看到扩展带有R
的原因。创建类时:
public class MyComparable<R>{
public boolean compare(R r1, R r2){
// Implementation
}
}
公共类MyComparable{
公共布尔比较(r1,r2){
//实施
}
}
您只是指示需要使用同一类的两个对象
要初始化该类,您将使用
List<String> strings = fillStrings();
int i = 1;
while(i < strings.size()){
boolean comparePreviousWithThis = new MyComparable<String>().compare(strings.get(i-1),strings.get(i));
}
List strings=fillStrings();
int i=1;
而(i
因此,您只指定了此类对象将具有的关系类型。这是一种双重分派模式是的-这就是为什么我接受它作为我关于双重分派的问题的答案:-)。我需要指导的是泛型的使用。这没有解决所问的问题。