gpt4 book ai didi

Java 泛型 - 接受 float 和 int

转载 作者:行者123 更新时间:2023-12-01 06:25:21 24 4
gpt4 key购买 nike

如何对我的类进行编程以接受整数和 float ,我想我需要使用泛型,对吗?

public class Vec2 {

private int x, y;

public Vec2(int xa, int ya) {
this.x = xa;
this.y = ya;
}
public Vec2() {
this(0, 0);
}
public Vec2(Vec2 vec) {
this(vec.x, vec.y);
}

public void addX(int xa) {
x+=xa; // I get an exception here when I try to use generics.
}
public void addY(int ya) {
y+=ya; // I get an exception here when I try to use generics.
}

有什么想法如何对我的类进行编程以接受 float 、整数和 double 吗?

最佳答案

目前,我们无法对 intdouble 等基元进行泛型,因此您将被迫使用盒装表示。为 intdouble 创建一个单独的类确实更容易。但如果您想使用泛型,可以通过以下方式以类型安全的方式(使用 java8)来实现:

public class Vec2<T> {

private final BinaryOperator<T> adder;

private T x, y;

private Vec2(BinaryOperator<T> adder, T x, T y) {
this.adder = adder;
this.x = x;
this.y = y;
}

public void addX(T xa) {
x = adder.apply(x, xa);
}

public void addY(T ya) {
y = adder.apply(y, ya);
}

public static Vec2<Integer> ofInt(Integer x, Integer y) {
return new Vec2<>(Integer::sum, x, y);
}

public static Vec2<Double> ofDouble(Double x, Double y) {
return new Vec2<>(Double::sum, x, y);
}
}
<小时/>
Vec2<Integer> intvec = Vec2.ofInt(5, 3);
intvec.addX(8);

Vec2<Double> dblvec = Vec2.ofDouble(5.2, 8.9);
dblvec.addY(-.9);

关于Java 泛型 - 接受 float 和 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30315402/

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