gpt4 book ai didi

java - java中的可变4维元组

转载 作者:行者123 更新时间:2023-12-01 22:54:13 25 4
gpt4 key购买 nike

是否有可变 4 维元组的 Java 实现?

MutableTuple4<Intger, Integer, Double, Double> a;
a.setFirst(a.getFirst() + 1);

最佳答案

没有内置的通用 Tuple4 类,但您可以轻松编写自己的通用任意长度 Tuple 类,并且有许多实现可用于基础代码,例如 apache.commons.MutableTriple (source code here)。

还有 javatuples 库,它提供长度最多为 10 个元素的不可变元组,您可以将其作为实现的基础(尽管我个人没有使用过它)。也许您可以问自己是否需要可变性?

事实上,正如其他人已经提到的那样,我强烈质疑具有任意值类型的可变对象的有效性 - 通常最好将特定概念封装在类中,而不是仅仅传递“值包”。

抛开注意事项不谈,这里有一个示例实现,基于上面提到的可以构建的 apache MutableTriple 类。与往常一样,在多线程环境中使用可变变量需要非常谨慎:不要以任何方式考虑此代码线程安全(我通常更喜欢不变性而不是可变性)。

public class MutableTuple4<A, B, C, D> { 

private static final long serialVersionUID = 1L;

public A first;
public B second;
public C third;
public D fourth;

public MutableTuple4(A a, B b, C c, D d) {
this.first = a;
this.second = b;
this.third = c;
this.fourth = d;
}

public A getFirst() {
return this.first;
}

public void setFirst(A first) {
this.first = first;
}

// remaining getters and setters here...
// etc...

@Override
public int hashCode() {
int hash = 3;
hash = 23 * hash + Objects.hashCode(this.first);
hash = 23 * hash + Objects.hashCode(this.second);
hash = 23 * hash + Objects.hashCode(this.third);
hash = 23 * hash + Objects.hashCode(this.fourth);
return hash;
}

@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Tuple<A, B, C, D> other = (Tuple<A, B, C, D>) obj;
if (!Objects.equals(this.first, other.first)) {
return false;
}
if (!Objects.equals(this.second, other.second)) {
return false;
}
if (!Objects.equals(this.third, other.third)) {
return false;
}
if (!Objects.equals(this.fourth, other.fourth)) {
return false;
}
return true;
}

}

关于java - java中的可变4维元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24336431/

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