65.9K
CodeProject is changing. Read more.
Home

ArrayList to File...

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.56/5 (9 votes)

Aug 18, 2010

CPOL

3 min read

viewsIcon

61745

downloadIcon

2069

Demonstrates a very simple way to create and save Multi-Dimensional (Virtual) ArrayLists to text file

Introduction

This is a simple demo on how to save Multi-Dimensional (Virtual) ArrayLists to text file, via a sample application.

application.png

About ArrayList

ArrayList implements the IList interface using an array whose size is dynamically increased as required, the capacity of an ArrayList is the number of elements the ArrayList can hold. As elements are added to an ArrayList, the capacity is automatically increased as required through reallocation; Elements in ArrayList collection can be accessed using an integer index. Indexes in this collection are zero-based; ArrayList accepts a null reference (Nothing in Visual Basic) as a valid value and allows duplicate elements. Using multidimensional arrays as elements in an ArrayList collection is not supported.

As the newer .NET runtimes offer better collections in System.Collections.Generic, ArrayList are not using in many cases.

singleDimArrayList.png

Advantages of ArrayList

  • Automatic Resizing
  • Convenient to use
  • ArrayList has methods that will add, insert, and remove a range of elements
  • Easy to create a thread-safe ArrayList using the Synchronized method
  • etc.

Disadvantages of ArrayList

  • ArrayList is restricted to a single dimension with a lower bound of zero, (but it can be used to store objects, we can use this feature to make the ArrayList Multi-Dimensional (Virtual)).
  • ArrayList is limited to accumulate only Objects
  • Performance wise very slow
  • etc.

Using the Code

This page does not display all the code, but the basic structure. Download the application source for a detailed investigation.

Basic Principle of Making an ArrayList Multi-Dimensional (Virtual)

As we know, ArrayList can be used to store objects. Here we are using this feature to make the ArrayList Multi-Dimensional (Virtual)) as shown below.

Method 1

'First declare a main ArrayList
Dim _MainList As New ArrayList
'Declare the inner ArrayList
Dim _InnerList As New ArrayList
'Adding data to the inner ArrayList
_InnerList.Add("MyData")
_InnerList.Add ("MoreData")

Now we have to add inner ArrayList to our main ArrayList, so in effect we have a Multi-Dimensional (Virtual) ArrayList.

_MainList.Add(_InnerList)
multiDimArrayList.png

Method 2

'First declare a main ArrayList
Dim _MainList As New ArrayList
'Declare the inner element as Object and add data to the inner element
Dim _InnerList As Object

Now we have to add inner element to our main ArrayList, so in effect we have a Multi-Dimensional (Virtual) ArrayList.

_MainList.Add(_InnerList)
singleDimArrayList.png

Method 3

This time we are going to use a structure as inner element.

Public Structure Contacts
  Private m_FirstName As String
  Private m_LastName As String
  Private m_Phone As String
        Public Property FirstName() As String
            Get
                Return m_FirstName
            End Get
            Set(ByVal value As String)
                m_FirstName = value
            End Set
        End Property
        Public Property LastName() As String
            Get
                Return m_LastName
            End Get
            Set(ByVal value As String)
                m_LastName = value
            End Set
        End Property
        Public Property Phone() As String
            Get
                Return m_Phone
            End Get
            Set(ByVal value As String)
                m_Phone = value
            End Set
        End Property
End Structure
'Then declare a main ArrayList
Dim _MainList As New ArrayList
'Declare the inner element as an instance of  Structure Contacts
Dim _InnerList As New Contacts
'Adding data to the inner element Contacts
_InnerList.FirstName = "Alex"
_InnerList.SecondName = "Tomy"
_InnerList.Phone = "123456789"

Now we have to add inner element to our main ArrayList, so in effect we have a Multi-Dimensional (Virtual) ArrayList.

_MainList.Add(_InnerList)
multiDimArrayListSTRUCTURE.png

Using the Code

This short article is presented as an example (Address Book) with simple steps to save Multi-Dimensional (Virtual) ArrayLists to text file.

The sample application consists of the following files:

solutionexp.png

Contacts.vb (Structure to manage contact details)

cLibrary.vb (Class used to accomplish save ArrayList {Multi-Dimensional} to file using an instance of the structure Contacts)

classdiagram.png

Step 1

First create the structure Contacts
(see Contacts.vb to understand how to..!!)

Step 2

Create a Class to save ArrayList {Multi-Dimensional} to file using an instance of the structure Contacts.

Friend Class cLibrary
'TO DO
End Class

Create a property called Library As ArrayList to manage the Multi-Dimensional ArrayList of structure Contacts.

Public Property Library() As ArrayList
            Get
                Return m_Library
            End Get
            Set(ByVal value As ArrayList)
                m_Library = value
            End Set
End Property

library.png

How to Save an ArrayList to Text File?

Public Sub WriteToFile(ByVal _FileName As String, ByVal _ArrayList As ArrayList)
            Dim oWrite As System.IO.StreamWriter
            oWrite = File.CreateText(_FileName)
            For i As Integer = 0 To _ArrayList.Count - 1
                oWrite.WriteLine(_ArrayList.Item(i))
                'here Overridden Function ToString is used to convert the structure 
                'Contacts to String value before writing to the text file
            Next
            oWrite.Close()
End Sub

How to Read a Text File to ArrayList?

Public Function ReadFromFile(ByVal _FileName As String) As ArrayList
            Dim oRead As System.IO.StreamReader
            Dim _ArrayList As New ArrayList
            Dim _Contacts As New Contacts
            _ArrayList.Clear()
            If (File.Exists(_FileName) = True) Then
                oRead = File.OpenText(_FileName)
                While oRead.Peek <> -1
                    _Contacts.FromString(oRead.ReadLine())
                    _ArrayList.Add(_Contacts)
                End While
                oRead.Close()
            End If
            Return _ArrayList
        End Function

(see cLibrary.vb to understand how to..!!)

Step 3

Public Class FrmMain
   Private _Lib As New cLibrary("ContactsLib.txt")
End Class

How to Add Item(s) to the Library from Form Class?

Dim _Contact As New Contacts
_Contact.FirstName = Trim(Me.TB_FirstName.Text)
_Contact.LastName = Trim(Me.TB_LastName.Text)
_Contact.Age = Val(Trim(Me.TB_Age.Text))
_Contact.PostBox = Trim(Me.TB_PostBox.Text)
_Contact.Street = Trim(Me.CB_Street.Text)
_Contact.City = Trim(Me.CB_City.Text)
_Contact.Phone = Trim(Me.TB_Phone.Text)
_Contact.Mobile = Trim(Me.TB_Mobile.Text)
_Contact.Email = Trim(Me.TB_Email.Text)
_Lib.Library.Add(_Contact)
_Lib.SaveLibrary()

How to Update an Existing Item in the Library from Form Class?

Dim _Index As Integer = _Lib.IndexOf(Me.CB_SelectContacts.Text)
Dim _Contact As New Contacts
_Contact.FirstName = Trim(Me.TB_FirstName.Text)
_Contact.LastName = Trim(Me.TB_LastName.Text)
_Contact.Age = Val(Trim(Me.TB_Age.Text))
_Contact.PostBox = Trim(Me.TB_PostBox.Text)
_Contact.Street = Trim(Me.CB_Street.Text)
_Contact.City = Trim(Me.CB_City.Text)
_Contact.Phone = Trim(Me.TB_Phone.Text)
_Contact.Mobile = Trim(Me.TB_Mobile.Text)
_Contact.Email = Trim(Me.TB_Email.Text)
_Lib.Library.Item(_Index) = _Contact
_Lib.SaveLibrary()

How to Remove an Existing Item in the Library from Form Class?

If (_Lib.Remove(Me.CB_SelectContacts.Text) = True) Then
            _Lib.SaveLibrary()
End If

How to Retrieve Details of an Existing Item in the Library from Form Class?

Dim _Contact As New Contacts
_Contact = _Lib.GetDetails(Me.CB_SelectContacts.Text)
With _Contact
        Me.TB_FullName.Text = .Name
        Me.TB_FirstName.Text = .FirstName
        Me.TB_LastName.Text = .LastName
        Me.TB_Age.Text = .Age
        Me.TB_PostBox.Text = .PostBox
        Me.CB_Street.Text = .Street
        Me.CB_City.Text = .City
        Me.TB_Phone.Text = .Phone
        Me.TB_Mobile.Text = .Mobile
        Me.TB_Email.Text = .Email
    End With
End Sub

(see FrmMain.vb to understand how to..!!)

Conclusion

There are probably bugs in my code; if you find any, please let me know and I will try to fix it. Comments and suggestions are most welcome.

Hope this can be helpful.
Happy programming!!!

History

  • 18th August, 2010: Initial post