gpt4 book ai didi

java - 泛型类型的运行方法

转载 作者:行者123 更新时间:2023-11-29 08:41:28 25 4
gpt4 key购买 nike

我不确定如何运行泛型 Point 的方法。假设有以下类

class Point1 {
double x, y;
public Point1 (double x_, double y_) {x=x_; y = y_;}
public double getX() {return x;}
public double getF1() {return x;}
}

class Point2 {
double lat, lon;
public Point2 (double lat_, double lon_) {lat = lat_; lon = lon_;}
public double getLat(){return lat;}
public double getF1() {return lat;}
}

共享同一个方法getF1()和一个方法

public <Point> void test(List<Point> points) {
for (Point point:points)
double x = point.getF1(); //Error Can not find symbol getF1()
}

public static void main (String [args]) {
List <Point1> points = new ArrayList<>();
test(points);
}

如何为泛型类型 Point (Point = Point1) 运行与 Point1 类型关联的方法 getF1()?是否可以使用接口(interface)

public interface ICoord {
double f();

public <Point> void test(List<Point> points, ICoord function) {
for (Point point:points)
double x = point.function.f();
}

最佳答案

看起来您只是在此处缺少 Point 的定义。

public interface Point {
double getF1();
}

这也意味着您的每个 Point 类都必须实现此接口(interface):

public class Point1 implements Point { }
public class Point2 implements Point { }

...然后您就可以使用它了,但您根本不需要通用参数。

public void test(List<Point> points) {
for (Point point: points) {
double x = point.getF1();
}
}

关于java - 泛型类型的运行方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39855485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com