www.boyet.com
Home
Tutorials

Tinkering with a TList

This article is an introduction to the TList, one of the most useful data structures in Delphi, and one that most programmers use at one time or another.

What we'll do in this talk is to firstly provide a quick overview of what TList is and how it works, and then, secondly, to show how you can use TList in various programming tasks.


What is it?

Well, let's jump right in. TList is a class that encapsulates an array of pointers. It is not a linked list as its name might suggest; it is an array. The elements of the array are pointers, or things that can be represented by pointers, like objects or strings for example. In this talk we'll be using objects, as they're the easiest to create and destroy and use.

The TList class has an array property called Items whereby you can access the various objects stored in the list. The Items property is the default array property, making it very easy to use a TList in the style of an array. You can easily iterate through the array and read and/or write the individual elements.

	var
	  MyList : TList;
	  MyButton : TButton;
	begin
	  {create the TList object}
	  MyList := TList.Create;
	  
	  {add a TObject to the list}
	  MyButton := TButton.Create(nil);
	  MyList.Add(pointer(MyButton));

	  {get the first item in the list}
	  MyButton := TButton(MyList[0]);

	  {destroy the list}
	  MyList.Free;
	end;
		

The class has range-checking built in as well: it's hard to access an element that does not exist-you automatically get an exception raised. You may have seen it: it's the infamous "List index out of bounds" error.

Unlike a normal array in Delphi, TList has some linked list type functionality as well. You can insert objects into the middle of the array, and you can delete objects from the array as well. When you insert a new object, all of the objects in the array from that point onwards are shifted along by one element to make some room for the new object, which then slots right in. Deleting an object works in a similar fashion. The objects from that point onwards are shifted back by one position to cover over the hole left by the disappearing object.

To be continued...




Copyright (c) Julian M Bucknall, 2000 Last modified: 30-Jun-2000 email: Webmaster