Delphi 泛型类学习(一)TList<Integer>

发布时间 2023-03-27 13:33:21作者: Rube's Delphi Blog
 1 var
 2   List: TList<Integer>;
 3   FoundIndex: Integer;
 4 
 5 begin
 6   { Create a new List. }
 7   List := TList<Integer>.Create;
 8   { Add a few values to the list. }
 9   List.AddRange([5, 1, 8, 2, 9, 14, 4, 5, 1]);
10 
11   writeln('Index of first 1 is ' + IntToStr(List.IndexOf(1)));
12   writeln('Index of last 1 is ' + IntToStr(List.LastIndexOf(1)));
13   writeln('Does List contains element 100? ' + BoolToStr(List.Contains(100)));
14 
15   { Add another element to the list. }
16   List.Add(100);
17 
18   writeln('There are ' + IntToStr(List.Count) + ' elements in the list.');
19 
20   { Remove the first occurrence of 1. }
21   List.Remove(1);
22   { Delete a few elements from position 0. }
23   List.Delete(0);
24   List.DeleteRange(0, 2);
25   { Extract the remaining 1 from the list. }
26   List.Extract(1);
27   { Set the capacity to the actual length. }
28   List.TrimExcess;
29   writeln('Capacity of the list is ' + IntToStr(List.Capacity));
30 
31   { Clear the list. }
32   List.Clear;
33   { Insert some elements. }
34   List.Insert(0, 2);
35   List.Insert(1, 1);
36   List.InsertRange(0, [6, 3, 8, 10, 11]);
37 
38   { Sort the list. }
39   List.Sort;
40 
41   { Binary search for the required element. }
42   if List.BinarySearch(6, FoundIndex) then
43     writeln('Found element 6 at index ' + IntToStr(FoundIndex));
44 
45   { Reverse the list. }
46   List.Reverse;
47   writeln('The element on position 0 is ' + IntToStr(List.Items[0]));
48   List.Free;
49   readln;
50 
51 end.