java:如何创建一个元组数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2754339/
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
java: how do I create an array of tuples
提问by kkkkk
how can I create an array of tuples in jsp (java) like (a:1, b:2) (c:3, d:4) ... ...
如何在 jsp (java) 中创建一个元组数组,如 (a:1, b:2) (c:3, d:4) ... ...
回答by Amir Rachum
Create a tuple class, something like:
创建一个元组类,例如:
class Tuple {
private Object[] data;
public Tuple (Object.. members) { this.data = members; }
public void get(int index) { return data[index]; }
public int getSize() { ... }
}
Then just create an array of Tuple instances.
然后只需创建一个元组实例数组。
回答by Carl
if you want an arbitrary size tuple, perl hash style, use a Map<K,V>(if you have a fixed type of keys values - your example looks like Map<Character,Integer>would work - otherwise use the raw type). Look up the java collections for more details about the various implementations.
如果您想要任意大小的元组,perl 哈希样式,请使用 a Map<K,V>(如果您有固定类型的键值 - 您的示例看起来Map<Character,Integer>可以工作 - 否则使用原始类型)。查找 java 集合以获取有关各种实现的更多详细信息。
Given those tuples, if you want to stick them in an sequential collection, I'd use a List (again, look up the collections library).
给定这些元组,如果你想把它们放在一个连续的集合中,我会使用一个列表(再次查找集合库)。
So you end up with
所以你最终得到
List<Map<K,V>> listOfTuples
if you need something more specific (like, you'll always have x1, x2, x3 in your tuple) consider making the maps be EnumMaps - you can restrict what keys you have, and if you specify a default (or some other constraint during creation) guarantee that something will come out.
如果您需要更具体的东西(例如,您的元组中将始终包含 x1、x2、x3),请考虑将映射设为EnumMaps - 您可以限制您拥有的键,并且如果您指定默认值(或其他一些约束)在创建期间)保证会出现一些东西。
回答by Mark
you could use the HashSet class.
你可以使用 HashSet 类。
回答by tzaman
There's no default pair / n-tuple class in Java; you'd have to roll your own.
Java 中没有默认的 pair/n-tuple 类;你必须自己动手。
回答by Eyal Schneider
If you are dealing with tuples of fixed size, with fixed names of the attributes, define a simple data class of your own, and then define the array of this class.
如果您正在处理固定大小的元组,具有固定的属性名称,请定义您自己的简单数据类,然后定义该类的数组。
If on the other hand you want the attribute names to be flexible and determined at runtime, use a Map structure. In your example above, it seems like HashMap<String,Integer> can do the job. You may want to wrap it in order to reduce its functionality, and maybe also add more specific functionality.
另一方面,如果您希望属性名称灵活并在运行时确定,请使用 Map 结构。在上面的示例中,似乎 HashMap<String,Integer> 可以完成这项工作。您可能希望包装它以减少其功能,也可能添加更多特定功能。

