Java中没有Pair<L,R>,有什么好理由吗?与这个c++构造等价的是什么?我宁愿避免重新实现我自己的。
似乎1.6提供了类似的东西(AbstractMap.SimpleEntry<K,V>),但这看起来相当复杂。
Java中没有Pair<L,R>,有什么好理由吗?与这个c++构造等价的是什么?我宁愿避免重新实现我自己的。
似乎1.6提供了类似的东西(AbstractMap.SimpleEntry<K,V>),但这看起来相当复杂。
这取决于你想用它来做什么。这样做的典型原因是在地图上迭代,为此你可以简单地这样做(Java 5+):
Map<String, Object> map = ... ; // just an example
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.printf("%s -> %s\n", entry.getKey(), entry.getValue());
}
在comp.lang.java的一个线程中。帮助,Hunter Gratzner给出了一些反对在Java中存在Pair结构的论点。主要的论点是类Pair不传递关于两个值之间关系的任何语义(您如何知道“first”和“second”的意思?)
一个更好的实践是为每个应用程序编写一个非常简单的类,就像Mike建议的那样。地图。Entry是一个在名称中包含其含义的对的例子。
总而言之,在我看来,最好有一个类Position(x,y),一个类Range(begin,end)和一个类Entry(key,value),而不是一个通用的Pair(first,second),它不告诉我它应该做什么。
HashMap兼容Pair类:
public class Pair<A, B> {
private A first;
private B second;
public Pair(A first, B second) {
super();
this.first = first;
this.second = second;
}
public int hashCode() {
int hashFirst = first != null ? first.hashCode() : 0;
int hashSecond = second != null ? second.hashCode() : 0;
return (hashFirst + hashSecond) * hashSecond + hashFirst;
}
public boolean equals(Object other) {
if (other instanceof Pair) {
Pair otherPair = (Pair) other;
return
(( this.first == otherPair.first ||
( this.first != null && otherPair.first != null &&
this.first.equals(otherPair.first))) &&
( this.second == otherPair.second ||
( this.second != null && otherPair.second != null &&
this.second.equals(otherPair.second))) );
}
return false;
}
public String toString()
{
return "(" + first + ", " + second + ")";
}
public A getFirst() {
return first;
}
public void setFirst(A first) {
this.first = first;
}
public B getSecond() {
return second;
}
public void setSecond(B second) {
this.second = second;
}
}
Pair是一个很好的东西,作为一个复杂泛型的基本构造单元,例如,这是我的代码:
WeakHashMap<Pair<String, String>, String> map = ...
它和Haskell的元组是一样的
这是Java。您必须使用描述性的类名和字段名创建自己定制的Pair类,不要介意通过编写hashCode()/equals()或一次又一次地实现Comparable来重新发明轮子。
实现Pair with的另一种方法。
Public immutable fields, i.e. simple data structure. Comparable. Simple hash and equals. Simple factory so you don't have to provide the types. e.g. Pair.of("hello", 1); public class Pair<FIRST, SECOND> implements Comparable<Pair<FIRST, SECOND>> { public final FIRST first; public final SECOND second; private Pair(FIRST first, SECOND second) { this.first = first; this.second = second; } public static <FIRST, SECOND> Pair<FIRST, SECOND> of(FIRST first, SECOND second) { return new Pair<FIRST, SECOND>(first, second); } @Override public int compareTo(Pair<FIRST, SECOND> o) { int cmp = compare(first, o.first); return cmp == 0 ? compare(second, o.second) : cmp; } // todo move this to a helper class. private static int compare(Object o1, Object o2) { return o1 == null ? o2 == null ? 0 : -1 : o2 == null ? +1 : ((Comparable) o1).compareTo(o2); } @Override public int hashCode() { return 31 * hashcode(first) + hashcode(second); } // todo move this to a helper class. private static int hashcode(Object o) { return o == null ? 0 : o.hashCode(); } @Override public boolean equals(Object obj) { if (!(obj instanceof Pair)) return false; if (this == obj) return true; return equal(first, ((Pair) obj).first) && equal(second, ((Pair) obj).second); } // todo move this to a helper class. private boolean equal(Object o1, Object o2) { return o1 == null ? o2 == null : (o1 == o2 || o1.equals(o2)); } @Override public String toString() { return "(" + first + ", " + second + ')'; } }
在我看来,Java中没有Pair,因为如果你想直接在Pair上添加额外的功能(例如Comparable),你必须绑定类型。在c++中,我们不在乎,如果组成一个pair的类型没有操作符<,则pair::operator <也不会被编译。
Comparable的一个例子:
public class Pair<F, S> implements Comparable<Pair<? extends F, ? extends S>> {
public final F first;
public final S second;
/* ... */
public int compareTo(Pair<? extends F, ? extends S> that) {
int cf = compare(first, that.first);
return cf == 0 ? compare(second, that.second) : cf;
}
//Why null is decided to be less than everything?
private static int compare(Object l, Object r) {
if (l == null) {
return r == null ? 0 : -1;
} else {
return r == null ? 1 : ((Comparable) (l)).compareTo(r);
}
}
}
/* ... */
Pair<Thread, HashMap<String, Integer>> a = /* ... */;
Pair<Thread, HashMap<String, Integer>> b = /* ... */;
//Runtime error here instead of compile error!
System.out.println(a.compareTo(b));
Comparable与编译时检查类型参数是否可比较的示例:
public class Pair<
F extends Comparable<? super F>,
S extends Comparable<? super S>
> implements Comparable<Pair<? extends F, ? extends S>> {
public final F first;
public final S second;
/* ... */
public int compareTo(Pair<? extends F, ? extends S> that) {
int cf = compare(first, that.first);
return cf == 0 ? compare(second, that.second) : cf;
}
//Why null is decided to be less than everything?
private static <
T extends Comparable<? super T>
> int compare(T l, T r) {
if (l == null) {
return r == null ? 0 : -1;
} else {
return r == null ? 1 : l.compareTo(r);
}
}
}
/* ... */
//Will not compile because Thread is not Comparable<? super Thread>
Pair<Thread, HashMap<String, Integer>> a = /* ... */;
Pair<Thread, HashMap<String, Integer>> b = /* ... */;
System.out.println(a.compareTo(b));
这很好,但是这次您不能在Pair中使用不可比较的类型作为类型参数。 你可能会在一些实用程序类中使用很多comparator for Pair,但是c++的人可能不会理解。另一种方法是在类型层次结构中编写很多类,在类型参数上有不同的边界,但是有太多可能的边界和它们的组合……
我能想到的最短的一对是以下,使用Lombok:
@Data
@AllArgsConstructor(staticName = "of")
public class Pair<F, S> {
private F first;
private S second;
}
它拥有@arturh答案的所有好处(除了可比性),它有hashCode, equals, toString和一个静态“构造函数”。
正如许多人已经指出的那样,Pair类是否有用实际上取决于用例。
我认为,对于私有帮助函数,如果使用Pair类可以使代码更具可读性,并且不值得花费精力创建另一个包含所有锅炉代码的值类,那么使用Pair类是完全合法的。
另一方面,如果您的抽象级别要求您清楚地记录包含两个对象或值的类的语义,那么您应该为它编写一个类。如果数据是业务对象,通常就是这种情况。
一如既往,这需要熟练的判断。
对于你的第二个问题,我推荐Apache Commons库中的Pair类。这些可能被认为是Java的扩展标准库:
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html
你可能还想看看Apache Commons的EqualsBuilder、HashCodeBuilder和ToStringBuilder,它们简化了为业务对象编写值类的过程。
我注意到所有的Pair实现都散布在这里,属性含义取决于两个值的顺序。当我想到一对时,我想到的是两件物品的组合,这两件物品的顺序不重要。下面是我对一个无序对的实现,使用hashCode和equals重写以确保集合中的期望行为。也可克隆。
/**
* The class <code>Pair</code> models a container for two objects wherein the
* object order is of no consequence for equality and hashing. An example of
* using Pair would be as the return type for a method that needs to return two
* related objects. Another good use is as entries in a Set or keys in a Map
* when only the unordered combination of two objects is of interest.<p>
* The term "object" as being a one of a Pair can be loosely interpreted. A
* Pair may have one or two <code>null</code> entries as values. Both values
* may also be the same object.<p>
* Mind that the order of the type parameters T and U is of no importance. A
* Pair<T, U> can still return <code>true</code> for method <code>equals</code>
* called with a Pair<U, T> argument.<p>
* Instances of this class are immutable, but the provided values might not be.
* This means the consistency of equality checks and the hash code is only as
* strong as that of the value types.<p>
*/
public class Pair<T, U> implements Cloneable {
/**
* One of the two values, for the declared type T.
*/
private final T object1;
/**
* One of the two values, for the declared type U.
*/
private final U object2;
private final boolean object1Null;
private final boolean object2Null;
private final boolean dualNull;
/**
* Constructs a new <code>Pair<T, U></code> with T object1 and U object2 as
* its values. The order of the arguments is of no consequence. One or both of
* the values may be <code>null</code> and both values may be the same object.
*
* @param object1 T to serve as one value.
* @param object2 U to serve as the other value.
*/
public Pair(T object1, U object2) {
this.object1 = object1;
this.object2 = object2;
object1Null = object1 == null;
object2Null = object2 == null;
dualNull = object1Null && object2Null;
}
/**
* Gets the value of this Pair provided as the first argument in the constructor.
*
* @return a value of this Pair.
*/
public T getObject1() {
return object1;
}
/**
* Gets the value of this Pair provided as the second argument in the constructor.
*
* @return a value of this Pair.
*/
public U getObject2() {
return object2;
}
/**
* Returns a shallow copy of this Pair. The returned Pair is a new instance
* created with the same values as this Pair. The values themselves are not
* cloned.
*
* @return a clone of this Pair.
*/
@Override
public Pair<T, U> clone() {
return new Pair<T, U>(object1, object2);
}
/**
* Indicates whether some other object is "equal" to this one.
* This Pair is considered equal to the object if and only if
* <ul>
* <li>the Object argument is not null,
* <li>the Object argument has a runtime type Pair or a subclass,
* </ul>
* AND
* <ul>
* <li>the Object argument refers to this pair
* <li>OR this pair's values are both null and the other pair's values are both null
* <li>OR this pair has one null value and the other pair has one null value and
* the remaining non-null values of both pairs are equal
* <li>OR both pairs have no null values and have value tuples <v1, v2> of
* this pair and <o1, o2> of the other pair so that at least one of the
* following statements is true:
* <ul>
* <li>v1 equals o1 and v2 equals o2
* <li>v1 equals o2 and v2 equals o1
* </ul>
* </ul>
* In any other case (such as when this pair has two null parts but the other
* only one) this method returns false.<p>
* The type parameters that were used for the other pair are of no importance.
* A Pair<T, U> can return <code>true</code> for equality testing with
* a Pair<T, V> even if V is neither a super- nor subtype of U, should
* the the value equality checks be positive or the U and V type values
* are both <code>null</code>. Type erasure for parameter types at compile
* time means that type checks are delegated to calls of the <code>equals</code>
* methods on the values themselves.
*
* @param obj the reference object with which to compare.
* @return true if the object is a Pair equal to this one.
*/
@Override
public boolean equals(Object obj) {
if(obj == null)
return false;
if(this == obj)
return true;
if(!(obj instanceof Pair<?, ?>))
return false;
final Pair<?, ?> otherPair = (Pair<?, ?>)obj;
if(dualNull)
return otherPair.dualNull;
//After this we're sure at least one part in this is not null
if(otherPair.dualNull)
return false;
//After this we're sure at least one part in obj is not null
if(object1Null) {
if(otherPair.object1Null) //Yes: this and other both have non-null part2
return object2.equals(otherPair.object2);
else if(otherPair.object2Null) //Yes: this has non-null part2, other has non-null part1
return object2.equals(otherPair.object1);
else //Remaining case: other has no non-null parts
return false;
} else if(object2Null) {
if(otherPair.object2Null) //Yes: this and other both have non-null part1
return object1.equals(otherPair.object1);
else if(otherPair.object1Null) //Yes: this has non-null part1, other has non-null part2
return object1.equals(otherPair.object2);
else //Remaining case: other has no non-null parts
return false;
} else {
//Transitive and symmetric requirements of equals will make sure
//checking the following cases are sufficient
if(object1.equals(otherPair.object1))
return object2.equals(otherPair.object2);
else if(object1.equals(otherPair.object2))
return object2.equals(otherPair.object1);
else
return false;
}
}
/**
* Returns a hash code value for the pair. This is calculated as the sum
* of the hash codes for the two values, wherein a value that is <code>null</code>
* contributes 0 to the sum. This implementation adheres to the contract for
* <code>hashCode()</code> as specified for <code>Object()</code>. The returned
* value hash code consistently remain the same for multiple invocations
* during an execution of a Java application, unless at least one of the pair
* values has its hash code changed. That would imply information used for
* equals in the changed value(s) has also changed, which would carry that
* change onto this class' <code>equals</code> implementation.
*
* @return a hash code for this Pair.
*/
@Override
public int hashCode() {
int hashCode = object1Null ? 0 : object1.hashCode();
hashCode += (object2Null ? 0 : object2.hashCode());
return hashCode;
}
}
这个实现已经经过了适当的单元测试,并且在Set和Map中的使用已经经过了尝试。
请注意,我并没有要求在公共领域发布这个。这是我为在应用程序中使用而编写的代码,因此如果您打算使用它,请避免直接复制,并在注释和名称上搞得一团糟。明白我的意思吗?
public class Pair<K, V> {
private final K element0;
private final V element1;
public static <K, V> Pair<K, V> createPair(K key, V value) {
return new Pair<K, V>(key, value);
}
public Pair(K element0, V element1) {
this.element0 = element0;
this.element1 = element1;
}
public K getElement0() {
return element0;
}
public V getElement1() {
return element1;
}
}
用法:
Pair<Integer, String> pair = Pair.createPair(1, "test");
pair.getElement0();
pair.getElement1();
不可变,只有一对!
http://www.javatuples.org/index.html怎么样?我发现它非常有用。
javatuples提供了从一到十个元素的元组类:
Unit<A> (1 element)
Pair<A,B> (2 elements)
Triplet<A,B,C> (3 elements)
Quartet<A,B,C,D> (4 elements)
Quintet<A,B,C,D,E> (5 elements)
Sextet<A,B,C,D,E,F> (6 elements)
Septet<A,B,C,D,E,F,G> (7 elements)
Octet<A,B,C,D,E,F,G,H> (8 elements)
Ennead<A,B,C,D,E,F,G,H,I> (9 elements)
Decade<A,B,C,D,E,F,G,H,I,J> (10 elements)
Apache Commons Lang 3.0+有几个Pair类: http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/package-summary.html
根据Java语言的性质,我认为人们实际上并不需要Pair,通常他们需要的是一个接口。这里有一个例子:
interface Pair<L, R> {
public L getL();
public R getR();
}
所以,当人们想要返回两个值时,他们可以这样做:
... //Calcuate the return value
final Integer v1 = result1;
final String v2 = result2;
return new Pair<Integer, String>(){
Integer getL(){ return v1; }
String getR(){ return v2; }
}
This is a pretty lightweight solution, and it answers the question "What is the semantic of a Pair<L,R>?". The answer is, this is an interface build with two (may be different) types, and it has methods to return each of them. It is up to you to add further semantic to it. For example, if you are using Position and REALLY want to indicate it in you code, you can define PositionX and PositionY that contains Integer, to make up a Pair<PositionX,PositionY>. If JSR 308 is available, you may also use Pair<@PositionX Integer, @PositionY Ingeger> to simplify that.
编辑: 这里我应该指出的一点是,上面的定义显式地将类型参数名和方法名联系起来。这是对那些认为Pair缺乏语义信息的人的回答。实际上,getL方法的意思是“给我对应于类型参数L的类型的元素”,这确实意味着什么。
编辑: 下面是一个简单的实用程序类,可以让生活变得更简单:
class Pairs {
static <L,R> Pair<L,R> makePair(final L l, final R r){
return new Pair<L,R>(){
public L getL() { return l; }
public R getR() { return r; }
};
}
}
用法:
return Pairs.makePair(new Integer(100), "123");
最大的问题可能是不能确保A和B上的不可变(参见如何确保类型参数是不可变的),因此hashCode()在插入到集合后可能会为相同的Pair给出不一致的结果(这将给出未定义的行为,参见定义可变字段中的equals)。对于一个特定的(非泛型的)Pair类,程序员可以通过仔细选择a和B为不可变来确保不可变性。
不管怎样,从@PeterLawrey的回答中清除泛型的警告(java 1.7):
public class Pair<A extends Comparable<? super A>,
B extends Comparable<? super B>>
implements Comparable<Pair<A, B>> {
public final A first;
public final B second;
private Pair(A first, B second) {
this.first = first;
this.second = second;
}
public static <A extends Comparable<? super A>,
B extends Comparable<? super B>>
Pair<A, B> of(A first, B second) {
return new Pair<A, B>(first, second);
}
@Override
public int compareTo(Pair<A, B> o) {
int cmp = o == null ? 1 : (this.first).compareTo(o.first);
return cmp == 0 ? (this.second).compareTo(o.second) : cmp;
}
@Override
public int hashCode() {
return 31 * hashcode(first) + hashcode(second);
}
// TODO : move this to a helper class.
private static int hashcode(Object o) {
return o == null ? 0 : o.hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Pair))
return false;
if (this == obj)
return true;
return equal(first, ((Pair<?, ?>) obj).first)
&& equal(second, ((Pair<?, ?>) obj).second);
}
// TODO : move this to a helper class.
private boolean equal(Object o1, Object o2) {
return o1 == o2 || (o1 != null && o1.equals(o2));
}
@Override
public String toString() {
return "(" + first + ", " + second + ')';
}
}
补充/更正非常欢迎:)特别是我不太确定我使用Pair<?, ? >。
有关为什么这种语法的更多信息,请参阅确保对象实现可比和详细解释如何在Java中实现一个通用的max(可比a,可比b)函数?
许多人都张贴对代码,可用作地图中的键…如果您试图使用一对作为哈希键(常用习语),请务必查看Guava的Table<R,C,V>: http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Table。对于图边,他们给出了下面的用法示例:
Table<Vertex, Vertex, Double> weightedGraph = HashBasedTable.create();
weightedGraph.put(v1, v2, 4);
weightedGraph.put(v1, v3, 20);
weightedGraph.put(v2, v3, 5);
weightedGraph.row(v1); // returns a Map mapping v2 to 4, v3 to 20
weightedGraph.column(v3); // returns a Map mapping v1 to 20, v2 to 5
Table将两个键映射到一个值,并单独为这两种类型的键提供有效的查找。我已经开始使用这个数据结构,而不是Map<Pair<K1,K2>, V>在我的代码的许多部分。有数组、树和其他用于密集和稀疏使用的实现,可以指定您自己的中间映射类。
对于Java这样的编程语言,大多数程序员用来表示类似对的数据结构的备用数据结构是两个数组,并且数据通过相同的索引访问
例如:http://www-igm.univ-mlv.fr/ lecroq /字符串/ node8.html # SECTION0080
这并不理想,因为数据应该绑定在一起,但结果也相当便宜。此外,如果你的用例需要存储坐标,那么最好构建自己的数据结构。
我的图书馆里就有这样的东西
public class Pair<First,Second>{.. }
尽管语法相似,但Java和c++有非常不同的范例。像Java一样写c++是糟糕的c++,像c++一样写Java是糟糕的Java。
使用像Eclipse这样基于反射的IDE,编写“pair”类的必要功能是快速而简单的。创建类,定义两个字段,使用各种“Generate XX”菜单选项在几秒钟内填写类。如果你想要Comparable界面,也许你必须很快地输入一个“compareTo”。
由于c++语言中有单独的声明/定义选项,代码生成器并不是很好,所以手工编写小的实用程序类更加费时乏味。由于pair是一个模板,您不必为不使用的函数付费,并且typedef功能允许为代码分配有意义的类型名,因此关于“无语义”的反对意见并不成立。
android提供了Pairclass (http://developer.android.com/reference/android/util/Pair.html),这里实现:
public class Pair<F, S> {
public final F first;
public final S second;
public Pair(F first, S second) {
this.first = first;
this.second = second;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Pair)) {
return false;
}
Pair<?, ?> p = (Pair<?, ?>) o;
return Objects.equal(p.first, first) && Objects.equal(p.second, second);
}
@Override
public int hashCode() {
return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
}
public static <A, B> Pair <A, B> create(A a, B b) {
return new Pair<A, B>(a, b);
}
}
pair是pair的一个简单实现。 它可以在jdk1.7.0_51\lib\tools.jar中找到。
除了org.apache.commons.lang3.tuple.Pair之外,它不仅仅是一个接口。
您可以使用谷歌的AutoValue库- https://github.com/google/auto/tree/master/value。
您创建一个非常小的抽象类,并使用@AutoValue注释它,注释处理器为您生成一个具有值语义的具体类。
地图。入口界面非常接近c++对。看看具体的实现,比如AbstractMap。SimpleEntry和AbstractMap。SimpleImmutableEntry 第一项是getKey(),第二项是getValue()。
为了方便起见,以下是一些具有多级元组的库:
JavaTuples。它只有1-10度的元组。 JavaSlang。0-8度的元组和许多其他功能性的东西。 jOOλ。0-16度的元组和其他一些功能性的好东西。(免责声明,我在维修公司工作) Functional Java。0-8度的元组和许多其他功能性的东西。
已经提到的其他库至少包含Pair元组。
具体来说,在函数式编程的上下文中,它使用了大量的结构类型,而不是名义类型(正如公认答案中提倡的那样),这些库及其元组非常方便。
好消息JavaFX有一个键值Pair。
只需添加JavaFX作为依赖项并导入JavaFX .util。对,并像在c++中那样简单地使用。
Pair <Key, Value>
e.g.
Pair <Integer, Integer> pr = new Pair<Integer, Integer>()
pr.get(key);// will return corresponding value
在Lombok的新版本中,你可以编译这个可爱的类:
@Value(staticConstructor = "of") public class Pair <E> {
E first, second;
}
并像这样使用它:Pair<Value> pairOfValues = Pair。(value1, value2);
Brian Goetz, Paul Sandoz和Stuart Marks在Devoxx'14的QA环节中解释了原因。
一旦值类型被引入,在标准库中使用泛型对类就会变成技术债。
请参见:Java SE 8是否有对或元组?
您可以使用javafx实用程序类Pair,它的作用与c++中的Pair <>相同。https://docs.oracle.com/javafx/2/api/javafx/util/Pair.html
@Andreas Krey的回答其实很好。任何Java给你带来困难的事情,你都不应该去做。
在我的经验中,Pair最常见的用途是一个方法的多个返回值和hashmap中的values(通常由字符串索引)。
在后一种情况下,我最近使用了一个数据结构,类似这样:
class SumHolder{MyObject trackedObject, double sum};
这是您的整个“Pair”类,与通用的“Pair”类的代码数量几乎相同,但具有描述性名称的优势。它可以在它使用的方法中定义,这将消除公共变量等典型问题。换句话说,对于这种用法,它绝对比一对更好(由于命名的成员),不会更差。
If you actually want a "Pair" for the key of a hashmap you are essentially creating a double-key index. I think this may be the one case where a "Pair" is significantly less code. It's not really easier because you could have eclipse generate equals/hash on your little data class, but it would be a good deal more code. Here a Pair would be a quick fix, but if you need a double-indexed hash who's to say you don't need an n-indexed hash? The data class solution will scale up, the Pair will not unless you nest them!
So the second case, returning from a method, is a bit harder. Your class needs more visibility (the caller needs to see it too). You can define it outside the method but inside the class exactly as above. At that point your method should be able to return a MyClass.SumHolder object. The caller gets to see the names of the returned objects, not just a "Pair". Note again that the "Default" security of package level is pretty good--it's restrictive enough that you shouldn't get yourself into too much trouble. Better than a "Pair" object anyway.
我能看到的另一种情况是使用一个公共api,为当前包之外的调用者提供返回值。为此,我只创建一个真正的对象——最好是不可变的。最终,调用者将共享此返回值,并且使其可变可能会出现问题。这是Pair对象更糟糕的另一种情况——大多数Pair不能被设置为不可变的。
所有这些情况的另一个优点是——java类扩展,我的sum类需要第二个sum和“Created”标记,当我完成时,我将不得不扔掉Pair并使用其他东西,但如果Pair有意义,我的4个值的类至少仍然有意义。
另一个简洁的lombok实现
import lombok.Value;
@Value(staticConstructor = "of")
public class Pair<F, S> {
private final F first;
private final S second;
}
虽然这个问题已经有十多年的历史了,但我觉得有必要提一下,从Java 14开始,Records可以为这个问题提供非常简单和轻量级的解决方案,而不需要任何形式的外部库或依赖项。
例如,以下记录类声明将是实现所需功能所需的全部内容:
record Pair<K, V>(K key, V value) { }
这样一个记录类可以这样使用:
// Declare a pair object containing two integers
var integerIntegerPair = new Pair<>(1, 2);
// Declare a pair object containing a String and an integer
var stringIntegerPair = new Pair<>("String", 20);
// Declare a pair object containing two other pairs!
var pairPairPair = new Pair<>(new Pair<>(1, 2), new Pair<>("String", 20));