值对的 Java 集合?(元组?)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/521171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
A Java collection of value pairs? (tuples?)
提问by DivideByHero
I like how Java has a Map where you can define the types of each entry in the map, for example <String, Integer>
.
我喜欢 Java 有一个 Map,您可以在其中定义地图中每个条目的类型,例如<String, Integer>
.
What I'm looking for is a type of collection where each element in the collection is a pair of values. Each value in the pair can have its own type (like the String and Integer example above), which is defined at declaration time.
我正在寻找的是一种集合,其中集合中的每个元素都是一对值。该对中的每个值都可以有自己的类型(如上面的 String 和 Integer 示例),这是在声明时定义的。
The collection will maintain its given order and will not treat one of the values as a unique key (as in a map).
该集合将保持其给定的顺序,并且不会将其中一个值视为唯一键(如在地图中)。
Essentially I want to be able to define an ARRAY of type <String,Integer>
or any other 2 types.
本质上,我希望能够定义类型<String,Integer>
或任何其他 2 种类型的 ARRAY 。
I realize that I can make a class with nothing but the 2 variables in it, but that seems overly verbose.
我意识到我可以创建一个只有 2 个变量的类,但这似乎过于冗长。
I also realize that I could use a 2D array, but because of the different types I need to use, I'd have to make them arrays of OBJECT, and then I'd have to cast all the time.
我也意识到我可以使用 2D 数组,但由于我需要使用不同的类型,我必须将它们设为 OBJECT 数组,然后我必须一直进行转换。
I only need to store pairs in the collection, so I only need two values per entry. Does something like this exist without going the class route? Thanks!
我只需要在集合中存储对,所以每个条目只需要两个值。如果不走课堂路线,是否存在这样的事情?谢谢!
采纳答案by Paul Brinkley
The Pair class is one of those "gimme" generics examples that is easy enough to write on your own. For example, off the top of my head:
Pair 类是那些很容易自己编写的“给我”泛型示例之一。例如,在我的头顶:
public class Pair<L,R> {
private final L left;
private final R right;
public Pair(L left, R right) {
assert left != null;
assert right != null;
this.left = left;
this.right = right;
}
public L getLeft() { return left; }
public R getRight() { return right; }
@Override
public int hashCode() { return left.hashCode() ^ right.hashCode(); }
@Override
public boolean equals(Object o) {
if (!(o instanceof Pair)) return false;
Pair pairo = (Pair) o;
return this.left.equals(pairo.getLeft()) &&
this.right.equals(pairo.getRight());
}
}
And yes, this exists in multiple places on the Net, with varying degrees of completeness and feature. (My example above is intended to be immutable.)
是的,这存在于网络上的多个地方,具有不同程度的完整性和功能。(我上面的例子是不可变的。)
回答by Dan Dyer
You could write a generic Pair<A, B> class and use this in an array or list. Yes, you have to write a class, but you can reuse the same class for all types, so you only have to do it once.
您可以编写一个通用的 Pair<A, B> 类并在数组或列表中使用它。是的,您必须编写一个类,但是您可以为所有类型重用同一个类,因此您只需编写一次。
回答by JMD
I was going to ask if you would not want to just use a List<Pair<T, U>>
? but then, of course, the JDK doesn't have a Pair<> class. But a quick Google found one on both Wikipedia, and forums.sun.com. Cheers
我想问你是否不想只使用List<Pair<T, U>>
? 但是,当然,JDK 没有 Pair<> 类。但是在Wikipedia和forums.sun.com上快速 Google 找到了一个。干杯
回答by Johannes Weiss
回答by Jeremy Rishel
The preferred solution as you've described it is a List of Pairs (i.e. List).
您所描述的首选解决方案是成对列表(即列表)。
To accomplish this you would create a Pair class for use in your collection. This is a useful utility class to add to your code base.
为此,您将创建一个 Pair 类以在您的集合中使用。这是一个有用的实用程序类,可以添加到您的代码库中。
The closest class in the Sun JDK providing functionality similar to a typical Pair class is AbstractMap.SimpleEntry. You could use this class rather than creating your own Pair class, though you would have to live with some awkward restrictions and I think most people would frown on this as not really the intended role of SimpleEntry. For example SimpleEntry has no "setKey()" method and no default constructor, so you may find it too limiting.
Sun JDK 中提供类似于典型 Pair 类的功能的最接近的类是 AbstractMap.SimpleEntry。您可以使用这个类而不是创建自己的 Pair 类,尽管您必须忍受一些尴尬的限制,而且我认为大多数人会认为这不是 SimpleEntry 真正的预期角色。例如,SimpleEntry 没有“setKey()”方法,也没有默认构造函数,因此您可能会发现它过于局限。
Bear in mind that Collections are designed to contain elements of a single type. Related utility interfaces such as Map are not actually Collections (i.e. Map does not implement the Collection interface). A Pair would not implement the Collection interface either but is obviously a useful class in building larger data structures.
请记住,集合旨在包含单一类型的元素。Map 等相关实用程序接口实际上并不是 Collections(即 Map 没有实现 Collection 接口)。Pair 也不会实现 Collection 接口,但显然是构建更大数据结构的有用类。
回答by Rene H.
What about com.sun.tools.javac.util.Pair?
com.sun.tools.javac.util.Pair 怎么样?
回答by JavaHelp4u
AbstractMap.SimpleEntry
AbstractMap.SimpleEntry
Easy you are looking for this:
很容易你正在寻找这个:
java.util.List<java.util.Map.Entry<String,Integer>> pairList= new java.util.ArrayList<>();
How can you fill it?
你怎么能填呢?
java.util.Map.Entry<String,Integer> pair1=new java.util.AbstractMap.SimpleEntry<>("Not Unique key1",1);
java.util.Map.Entry<String,Integer> pair2=new java.util.AbstractMap.SimpleEntry<>("Not Unique key2",2);
pairList.add(pair1);
pairList.add(pair2);
This simplifies to:
这简化为:
Entry<String,Integer> pair1=new SimpleEntry<>("Not Unique key1",1);
Entry<String,Integer> pair2=new SimpleEntry<>("Not Unique key2",2);
pairList.add(pair1);
pairList.add(pair2);
And, with the help of a createEntry
method, can further reduce the verbosity to:
并且,在createEntry
方法的帮助下,可以进一步减少冗长到:
pairList.add(createEntry("Not Unique key1", 1));
pairList.add(createEntry("Not Unique key2", 2));
Since ArrayList
isn't final, it can be subclassed to expose an of
method (and the aforementioned createEntry
method), resulting in the syntactically terse:
由于ArrayList
不是最终的,它可以被子类化以公开一个of
方法(和上述createEntry
方法),从而在语法上简洁:
TupleList<java.util.Map.Entry<String,Integer>> pair = new TupleList<>();
pair.of("Not Unique key1", 1);
pair.of("Not Unique key2", 2);
回答by changed
Apache common lang3 has Pair class and few other libraries mentioned in this thread What is the equivalent of the C++ Pair<L,R> in Java?
Apache common lang3 有 Pair 类和这个线程中提到的其他几个库Java 中 C++ Pair<L,R> 的等价物是什么?
Example matching the requirement from your original question:
匹配原始问题要求的示例:
List<Pair<String, Integer>> myPairs = new ArrayList<Pair<String, Integer>>();
myPairs.add(Pair.of("val1", 11));
myPairs.add(Pair.of("val2", 17));
//...
for(Pair<String, Integer> pair : myPairs) {
//following two lines are equivalent... whichever is easier for you...
System.out.println(pair.getLeft() + ": " + pair.getRight());
System.out.println(pair.getKey() + ": " + pair.getValue());
}
回答by simbo1905
Expanding on the other answers a generic immutable Pair should have a static method to avoid cluttering your code with the call to the constructor:
扩展其他答案,一个通用的不可变 Pair 应该有一个静态方法,以避免调用构造函数使代码混乱:
class Pair<L,R> {
final L left;
final R right;
public Pair(L left, R right) {
this.left = left;
this.right = right;
}
static <L,R> Pair<L,R> of(L left, R right){
return new Pair<L,R>(left, right);
}
}
if you name the static method "of" or "pairOf" the code becomes fluent as you can write either:
如果您将静态方法命名为“of”或“pairOf”,则代码变得流畅,因为您可以编写:
list.add(Pair.of(x,y)); // my preference
list.add(pairOf(x,y)); // use with import static x.y.Pair.pairOf
its a real shame that the core java libraries are so sparse on such things that you have to use commons-lang or other 3rd parties to do such basic stuff. yet another reason to upgrade to scala...
真的很遗憾,核心 Java 库在此类事情上如此稀少,以至于您必须使用 commons-lang 或其他 3rd 方来做这些基本的事情。升级到 Scala 的另一个原因......
回答by Bobak_KS
Apache Crunchalso has a Pair
class:
http://crunch.apache.org/apidocs/0.5.0/org/apache/crunch/Pair.html
Apache Crunch也有一个Pair
类:http:
//crunch.apache.org/apidocs/0.5.0/org/apache/crunch/Pair.html