Search code examples
delphi

Why does TDictionary store values out of order?


I'm populating a Dictionary with some values and would like to get them back in the same exact order I populated them.

Somehow it doesn't seem to be working, when I iterate through items they are sorted by a non logic order (IMDO).

Once the following program is run:

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils, System.Generics.Collections;
var
  Dictionary: TDictionary<LongWord, string>;
  aPair: TPair<LongWord, string>;
begin
  Dictionary := TDictionary<LongWord, string>.Create;
  Dictionary.add(1, 'First Item');
  Dictionary.add(2, 'Second Item');
  Dictionary.add(3, 'Third Item');
  Dictionary.add(4, 'Forth Item');
  Dictionary.add(5, 'Fifth Item');
  Dictionary.add($FFFFFFFF, 'Longword Item');

  for aPair in Dictionary do
    writeln(aPair.Value);

  readln;
end.

I got the following results:

Forth Item
Longword Item
First Item
Third Item
Second Item
Fifth Item

Am I doing something wrong?


Solution

  • The Delphi dictionary class is unordered. It behaves as designed. If you wish to maintain the order then you need to use an ordered data structure. For instance an array or a list.

    If you wish to have ordered access as well as O(1) lookup then you would need to maintain two collections in tandem. One an array or list for ordered access, and in tandem a dictionary for O(1) lookup. Or, alternatively, find a library that offers an ordered dictionary implementation.