我有以下问题。我有一个包含名为Entry的对象的链表或位置列表。每个条目都存储一个键和一个值对。我想制作另一个链表来从该列表中获取密钥。我想出了一个方法来做到这一点,但是由于某种原因,我打印密钥列表时没有表示我添加它们的顺序。我有以下两种方法:
public PositionalList1<K> keySet() //I prnted position by position while adding and it worked. I also tested addAfter with positionalList1 class and it worked
{
PositionInterface<Entry> iterator = map.first(); //gets first position in the Entry List
PositionInterface<K> first = keyList.addFirst((K)iterator.getData().getKey()); //adds to list containing just keys the key from the Entry list(getData is just a method that returns whatever object is stored at the node, in this case a Entry Object)
iterator = map.after(iterator); //go to next node in Entry list
for(int i=0;i<size-1;i++) //get rest of keys
{
PositionInterface<K> p = keyList.addAfter(first,(K)iterator.getData().getKey());
iterator = map.after(iterator);
}
return keyList;
}
public void printKeySet(PositionalList1 list) //print key list
{
PositionInterface p = list.first();
for(int i=0; i<list.size();i++)
{
System.out.println("Key : " + p.getData());
p = list.after(p);
}
}
keySet()方法返回仅包含键的列表,而printKeySet获取KeySet()的结果并打印整个键列表。我使用以下主程序对此进行了测试:
OrderedMapL<Integer,String> map2 = new OrderedMapL<Integer,String>();
map2.put(2,"A");//adds (2,A)
map2.put(5,"B");//adds(5,B)
map2.put(1,"C");//adds(1,C)
map2.put(4,"D");//adds(4,D)
map2.put(3,"E");//adds(3,E)
map2.remove(2); //removes (2,A)
这导致了(1,C)(2,A)等的有序列表,并且条目本身按此顺序打印正常。调用以下内容时会出现问题:
PositionalList1<Integer> keyList = map2.keySet();
map2.printKeySet(keyList);
由于某种原因,按键按顺序打印:1,5,4,3而不是1,3,4,5,我不明白为什么。任何帮助将不胜感激。
答案 0 :(得分:1)
问题在于这一行:
PositionInterface<K> p = keyList.addAfter(first,(K)iterator.getData().getKey());
您不应在first
之后添加。这就是你订单错误的原因。
如果密钥是1, 3, 4, 5
,那么您正在添加它:
1
1 3
1 4 3
1 5 4 3
这是因为你是在第一个元素之后添加它。
如果我理解你的代码你应该改变它:
// I suspect that #addFirst method returns added list element
PositionInterface<K> last = keyList.addFirst((K) iterator.getData().getKey());
iterator = map.after(iterator);
for(int i = 0; i < size - 1; i++)
{
// I suspect that #addAfter method returns added list element
PositionInterface<K> last = keyList.addAfter(last, (K) iterator.getData().getKey());
iterator = map.after(iterator);
}