Adding byte arrays to an ArrayList

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • JonJacobs
    New Member
    • Aug 2007
    • 22

    Adding byte arrays to an ArrayList

    When I add a series of byte arrays to an array list, then I read them back, all the arraylist byte array elements are identical to the last byte array entry. What is wrong? The following code will reproduce the problem.

    Thanks,

    Jon Jacobs

    [CODE=vbnet]Imports System.Text
    Public Class Form1

    Private Sub Button1_Click(B yVal sender As System.Object, ByVal e As System.EventArg s) Handles Button1.Click
    Dim a(9) As Byte
    Dim al As ArrayList = New ArrayList

    Dim L As Integer
    Dim total As Integer = 0
    For i As Integer = 0 To 5
    L = read(i, a)
    total = total + L
    al.Add(a) 'at this point the value of a is correct
    Next
    al.Add(L)
    al.Add(total)

    Dim b0() As Byte = al(0)
    Dim b1() As Byte = al(1)
    Dim b2() As Byte = al(2)
    Dim b3() As Byte = al(3)
    Dim b4() As Byte = al(4)
    Dim b5() As Byte = al(5)

    Dim result(54) As Byte ' = ArBldr(al)
    Buffer.BlockCop y(b0, 0, result, 0, 10)
    Buffer.BlockCop y(b1, 0, result, 10, 10)
    Buffer.BlockCop y(b2, 0, result, 20, 10)
    Buffer.BlockCop y(b3, 0, result, 30, 10)
    Buffer.BlockCop y(b4, 0, result, 40, 10)
    Buffer.BlockCop y(b5, 0, result, 50, 5)

    Dim S As String = Encoding.ASCII. GetString(resul t)

    MessageBox.Show (S)
    End Sub

    Private Function read(ByVal index As Integer, ByVal b() As Byte) As Integer
    Dim buf() As Byte
    Select Case index
    Case 0
    buf = Encoding.ASCII. GetBytes("AAAAA AAAAA")
    Buffer.BlockCop y(buf, 0, b, 0, buf.Length)
    Return buf.Length
    Case 1
    buf = Encoding.ASCII. GetBytes("BBBBB BBBBB")
    Buffer.BlockCop y(buf, 0, b, 0, buf.Length)
    Return buf.Length
    Case 2
    buf = Encoding.ASCII. GetBytes("CCCCC CCCCC")
    Buffer.BlockCop y(buf, 0, b, 0, buf.Length)
    Return buf.Length
    Case 3
    buf = Encoding.ASCII. GetBytes("DDDDD DDDDD")
    Buffer.BlockCop y(buf, 0, b, 0, buf.Length)
    Return buf.Length
    Case 4
    buf = Encoding.ASCII. GetBytes("EEEEE EEEEE")
    Buffer.BlockCop y(buf, 0, b, 0, buf.Length)
    Return buf.Length
    Case 5
    buf = Encoding.ASCII. GetBytes("FFFFF ")
    Buffer.BlockCop y(buf, 0, b, 0, buf.Length)
    Return buf.Length
    Case Else
    Return 0
    End Select
    End Function

    End Class[/CODE]
Working...