我正在寻找一个具有键值关联的java类,但不使用哈希.这是我目前正在做的事情:
Hashtable.Hashtable.entrySet().Map.Entry迭代器.Module根据值创建类型(自定义类)的对象.这个问题是我无法控制返回值的顺序,所以我不能以给定的顺序显示值(不对代码进行硬编码).
我会使用一个ArrayList或Vector为此,但稍后在代码中我需要抓取Module给定Key 的对象,我无法使用ArrayList或Vector.
有没有人知道一个可以执行此操作的免费/开源Java类,或者Hashtable根据添加时间来获取值的方法?
谢谢!
我正在尝试在Map中放入一些键值,并尝试以与插入时相同的顺序检索它们.例如下面是我的代码
import java.util.*;
import java.util.Map.Entry;
public class HashMaptoArrayExample {
public static void main(String args[])
{
Map<String,Integer> map= new HashMap<String,Integer>();
// put some values into map
map.put("first",1);
map.put("second",2);
map.put("third",3);
map.put("fourth",4);
map.put("fifth",5);
map.put("sixth",6);
map.put("seventh",7);
map.put("eighth",8);
map.put("ninth",9);
Iterator iterator= map.entrySet().iterator();
while(iterator.hasNext())
{
Entry entry =(Entry)iterator.next();
System.out.println(" entries= "+entry.getKey().toString());
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想检索如下的密钥
first second third fourth fifth sixth .....
Run Code Online (Sandbox Code Playgroud)
但它在我的输出中以一些随机顺序显示如下
OUTPUT
ninth eigth fifth first sixth seventh third fourth second
Run Code Online (Sandbox Code Playgroud) 我想要一个在Java中实现Map和List接口的对象.这个想法类似于这个问题中的问题:Java Ordered Map
我想将名称/值对添加到列表中并使列表保留序列,但也能够按名称进行查找:
foo.put("name0", "value0");
foo.put("name1", "value1");
foo.get(1); --> Map.Entry("name1", "value1")
foo.get("name0"); --> "value0"
Run Code Online (Sandbox Code Playgroud)
这是问题所在:当我创建这个类时:
class Foo implements Map, List {
// add all methods here
}
Run Code Online (Sandbox Code Playgroud)
我收到编译错误:
"The return type is incompatible with Map.remove(Object)"
public boolean remove(Object o) {
return false;
}
Run Code Online (Sandbox Code Playgroud)
如果我没有实现Map和List接口,那么有许多Java集合方法无法在此数据结构上使用.
(另外,上面的Java Ordered Map中提出的解决方案不起作用的原因是LinkedHashMap没有get(int)方法.不能通过索引选择条目.)
我需要一个提供键-值映射关系的数据结构,例如和Map,但还允许我基于(int)索引(例如myKey = myDS.get(index))来获取键,而不必遍历数据结构以使键位于所需的位置指数。
我考虑过使用LinkedHashMap,但没有找到在给定索引处获取密钥的方法。我想念什么LinkedHashMap吗?还是我可以使用其他数据结构?
编辑:
这不是重复。另一个问题的正确答案是使用某种方法SortedMap; 但是,这不是对这个问题的正确答案,因为我希望能够Entry通过Integer索引从数据结构中检索到,这在任何Java库中都不支持。