Click here to Skip to main content
11,493,233 members (62,516 online)
Click here to Skip to main content

ArrayList to File...

, 18 Aug 2010 CPOL 27.8K 1.5K 12
Rate this:
Please Sign up or sign in to vote.
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Koshy Panicker John
Software Developer (Senior)
India India
No Biography provided

Comments and Discussions

 
GeneralNice article Pin
Shane Story25-Aug-10 8:02
memberShane Story25-Aug-10 8:02 
GeneralMy vote of 1 Pin
J a a n s19-Aug-10 4:14
memberJ a a n s19-Aug-10 4:14 
GeneralMy vote of 1 Pin
Michael Sterk18-Aug-10 20:23
memberMichael Sterk18-Aug-10 20:23 
GeneralMy vote of 2 Pin
ScruffyDuck18-Aug-10 17:40
memberScruffyDuck18-Aug-10 17:40 
GeneralMy vote of 2 Pin
karabax18-Aug-10 7:32
memberkarabax18-Aug-10 7:32 
GeneralMy vote of 2 Pin
luisnike1918-Aug-10 7:15
memberluisnike1918-Aug-10 7:15 
GeneralMy vote of 2 Pin
John Brett18-Aug-10 3:31
memberJohn Brett18-Aug-10 3:31 
GeneralI agree with digital man... Pin
Dave Kreskowiak18-Aug-10 3:02
mvpDave Kreskowiak18-Aug-10 3:02 
Generalvote for make it public Pin
Pranay Rana18-Aug-10 2:59
memberPranay Rana18-Aug-10 2:59 
GeneralMy vote of 5 Pin
Pranay Rana18-Aug-10 2:59
memberPranay Rana18-Aug-10 2:59 
GeneralGood Work..& very colorful article. Pin
Md. Marufuzzaman18-Aug-10 2:51
mvpMd. Marufuzzaman18-Aug-10 2:51 
GeneralSerialize Pin
Trollslayer18-Aug-10 2:39
mentorTrollslayer18-Aug-10 2:39 
GeneralHmm Pin
digital man18-Aug-10 0:19
memberdigital man18-Aug-10 0:19 
GeneralRe: Hmm Pin
Ajay Vijayvargiya18-Aug-10 0:39
memberAjay Vijayvargiya18-Aug-10 0:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150520.1 | Last Updated 18 Aug 2010
Article Copyright 2010 by Koshy Panicker John
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid