473,386 Members | 1,830 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

How to access an array element in a member of ArrayList?

Hi everyone,
I have an ArrayList whose members are classes. These classes are derived from a same base class. The base class has a floating point array and a string. How do I access each element in the floating point array in a member of the ArrayList?
Any help would be greatly appreciated.

Haobin

Nov 16 '05 #1
9 4024
Haobin <an*******@discussions.microsoft.com> wrote:
I have an ArrayList whose members are classes. These classes are
derived from a same base class. The base class has a floating point
array and a string. How do I access each element in the floating
point array in a member of the ArrayList?
Any help would be greatly appreciated.


As always in programming, the trick is to break the problem down:

1) How do I get an element in my array list as the base class?
2) How do I access the floating point array in an instance of my base
class?
3) How do I access each element in a floating point array?
1) is easy - just cast:

BaseClass foo = (BaseClass) myArrayList[index];

2) depends on your base class

3) is easy - just index:

float f = myFloatArray[index];

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2
Haobin,

I assume this is the scenario you are talking about...
----------------------------------------------------------------------------
--------------------
class SomeObject
{
public float fMyNumber; // or is it an array of floats? doesn't matter
either way.
public string szMyString;
...
}

ArrayList aryOfObjects... // contains, or will contain loads of SomeObjects
----------------------------------------------------------------------------
--------------------
void SomeMethodSomewhere()
{

//
// for all objects in the array
//

SomeObject so;
for ( int a = 0; a < aryOfObjects.Count; a++ )
{
if ( aryOfObjects[a] is SomeObject )
{
so = (SomeObject)aryOfObjects[a];
listbox1.Items.Add ( so.fMyNumber.ToString() ); // add float to
some predifined list
listbox2.Items.Add ( so.szMyString.ToString() ); // add string
to some predifined list
}
else
{
// report some error?
continue;
}

}

}
----------------------------------------------------------------------------
--------------------

Does that make sense? Of course it's better code practice to keep your
member variables private, and access them through properties.
Let me know if you have any more probs.

Dan.

"Haobin" <an*******@discussions.microsoft.com> wrote in message
news:04**********************************@microsof t.com...
Hi everyone,
I have an ArrayList whose members are classes. These classes are derived from a same base class. The base class has a floating point array and a
string. How do I access each element in the floating point array in a member
of the ArrayList? Any help would be greatly appreciated.

Haobin

Nov 16 '05 #3
Below is a small twist that can be slightly more efficient I guess as you
check the type and cast at same time.

SomeObject so = null;
for ( int a = 0; a < aryOfObjects.Count; a++ )
{
so = aryOfObjects[a] as SomeObject;
if ( so == null )
throw new MyException("foo");
listbox1.Items.Add(so.fMyNumber.ToString());
....
}

--
William Stacey, MVP
void SomeMethodSomewhere()
{

//
// for all objects in the array
//

SomeObject so;
for ( int a = 0; a < aryOfObjects.Count; a++ )
{
if ( aryOfObjects[a] is SomeObject )
{
so = (SomeObject)aryOfObjects[a];
listbox1.Items.Add ( so.fMyNumber.ToString() ); // add float to some predifined list
listbox2.Items.Add ( so.szMyString.ToString() ); // add string
to some predifined list
}
else
{
// report some error?
continue;
}

}

}
-------------------------------------------------------------------------- -- --------------------

Does that make sense? Of course it's better code practice to keep your
member variables private, and access them through properties.
Let me know if you have any more probs.

Dan.

"Haobin" <an*******@discussions.microsoft.com> wrote in message
news:04**********************************@microsof t.com...
Hi everyone,
I have an ArrayList whose members are classes. These classes are derived from a same base class. The base class has a floating point array and a
string. How do I access each element in the floating point array in a

member of the ArrayList?
Any help would be greatly appreciated.

Haobin



Nov 16 '05 #4
Hi Jon and Daniel
Thanks for your replies
I modified my code based on your replies. It passed compilation but I got "InvalidCastException" in runtime at the step 1 in Jon's reply and at the line "so = (SomeObject)aryOfObjects[a];" in Daniel's reply. What could be wrong
I appreciate your help

Haobi

----- Daniel Bass wrote: ----

Haobin

I assume this is the scenario you are talking about..
---------------------------------------------------------------------------
-------------------
class SomeObjec

public float fMyNumber; // or is it an array of floats? doesn't matte
either way
public string szMyString
..
ArrayList aryOfObjects... // contains, or will contain loads of SomeObject
---------------------------------------------------------------------------
-------------------
void SomeMethodSomewhere(
/
// for all objects in the arra
/

SomeObject so
for ( int a = 0; a < aryOfObjects.Count; a++

if ( aryOfObjects[a] is SomeObject

so = (SomeObject)aryOfObjects[a]
listbox1.Items.Add ( so.fMyNumber.ToString() ); // add float t
some predifined lis
listbox2.Items.Add ( so.szMyString.ToString() ); // add strin
to some predifined lis

els

// report some error
continue

---------------------------------------------------------------------------
-------------------

Does that make sense? Of course it's better code practice to keep you
member variables private, and access them through properties
Let me know if you have any more probs

Dan

"Haobin" <an*******@discussions.microsoft.com> wrote in messag
news:04**********************************@microsof t.com..
Hi everyone
I have an ArrayList whose members are classes. These classes are derive from a same base class. The base class has a floating point array and
string. How do I access each element in the floating point array in a membe
of the ArrayList Any help would be greatly appreciated
Haobi

Nov 16 '05 #5
Haobin <an*******@discussions.microsoft.com> wrote:
Thanks for your replies.
I modified my code based on your replies. It passed compilation but I
got "InvalidCastException" in runtime at the step 1 in Jon's reply
and at the line "so = (SomeObject)aryOfObjects[a];" in Daniel's
reply. What could be wrong?
I appreciate your help.


Basically exactly what the exception says: you're trying to cast
something which isn't an instance of your class.

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #6
Hi Jon, Daniel and William
Thank you very much
Here is my test code
Haobi

using System
using System.Drawing
using System.Collections
using System.Windows.Forms
using System.Data

namespace DrawTes

public class Form1 : System.Windows.Forms.For

public ArrayList alDataSets = new ArrayList()

private System.Windows.Forms.Button button1

private void button1_Click(object sender, System.EventArgs e

float expData1,expData2
Random rand = new Random()

expData1 = (float)rand.NextDouble()
expData2 = (float)rand.NextDouble()

DataSets dataset1 = new DataSets();
dataset1.fData = expData1
dataset1.strDesc = "X"
alDataSets.Add(expData1)

DataSets dataset2 = new DataSets();
dataset2.fData = expData2
dataset2.strDesc = "Y"
alDataSets.Add(expData2)

label1.Text = alDataSets.Count.ToString()

DataSets dataset3
dataset3= null
dataset3 = (DataSets)alDataSets[0]; //get "System.InvalidCastException
string strFirst
strFirst = dataset3.strDesc
label2.Text = strFirst

DataSets dataset4
dataset4 = (DataSets)alDataSets[1]; //get "System.InvalidCastException
string strSecond
strSecond = dataset4.strDesc
label3.Text = strSecond

//the base clas
using System

namespace DrawTes

public class DataSet

public DataSets(

private float arData
private string desc

public string strDes

get{return desc;
set{desc = value;

public float fDat

get{return arData;
set{arData = value;

----- Jon Skeet [C# MVP] wrote: ----

Haobin <an*******@discussions.microsoft.com> wrote
Thanks for your replies
I modified my code based on your replies. It passed compilation but
got "InvalidCastException" in runtime at the step 1 in Jon's repl
and at the line "so = (SomeObject)aryOfObjects[a];" in Daniel'
reply. What could be wrong
I appreciate your help


Basically exactly what the exception says: you're trying to cast
something which isn't an instance of your class

Could you post a short but complete program which demonstrates th
problem

See http://www.pobox.com/~skeet/csharp/complete.html for details o
what I mean by that

--
Jon Skeet - <sk***@pobox.com
http://www.pobox.com/~skee
If replying to the group, please do not mail me to

Nov 16 '05 #7
Haobin <an*******@discussions.microsoft.com> wrote:
Hi Jon, Daniel and William,
Thank you very much.
Here is my test code.
The relevant lines are:
expData1 = (float)rand.NextDouble();
expData2 = (float)rand.NextDouble();
<snip>
alDataSets.Add(expData1);
<snip>
alDataSets.Add(expData2);
dataset3 = (DataSets)alDataSets[0];
//get "System.InvalidCastException"


So you've added two *floats* to the ArrayList, but then you're trying
to cast them to DataSets.

I think you actually meant:

alDataSets.Add(dataSet1);

etc

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #8
"Haobin" wrote...

You get the InvalidCastException because you try to cast to a type which the
object isn't castable to.

The reason for this is found higher up in the code, where we see that you
don't actuallt put objects of that type into the ArrayList:
DataSets dataset1 = new DataSets();
dataset1.fData = expData1;
alDataSets.Add(expData1); // <-

DataSets dataset2 = new DataSets();
dataset2.fData = expData2;
alDataSets.Add(expData2); // <-
You have put two floats into the ArrayList, not the whole DataSets.
dataset3 = (DataSets)alDataSets[0]; //get "System.InvalidCastException"


The lines I've marked above should probably be the following instead:

alDataSets.Add(dataset1b);

alDataSets.Add(dataset2);

// Bjorn A
Nov 16 '05 #9
William,

I've not really come across the "as" keyword in C#. Suppose never needed to
use it, so never find it.

I'd still go for my solution to it, just from a readability point of view...
it seems most logical, well to me anyway, to say if this object is a certain
type, then assign it, rather than assigning the object as a type to another
object, and if that fails then the object wasn't of the type we specified.

As far as efficiency goes, it seems negligible.

Interesting though.
Thanks.
Dan.

"William Stacey [MVP]" <st***********@mvps.org> wrote in message
news:%2****************@TK2MSFTNGP09.phx.gbl...
Below is a small twist that can be slightly more efficient I guess as you
check the type and cast at same time.

SomeObject so = null;
for ( int a = 0; a < aryOfObjects.Count; a++ )
{
so = aryOfObjects[a] as SomeObject;
if ( so == null )
throw new MyException("foo");
listbox1.Items.Add(so.fMyNumber.ToString());
....
}

--
William Stacey, MVP
void SomeMethodSomewhere()
{

//
// for all objects in the array
//

SomeObject so;
for ( int a = 0; a < aryOfObjects.Count; a++ )
{
if ( aryOfObjects[a] is SomeObject )
{
so = (SomeObject)aryOfObjects[a];
listbox1.Items.Add ( so.fMyNumber.ToString() ); // add float

to
some predifined list
listbox2.Items.Add ( so.szMyString.ToString() ); // add string to some predifined list
}
else
{
// report some error?
continue;
}

}

}


--------------------------------------------------------------------------
--
--------------------

Does that make sense? Of course it's better code practice to keep your
member variables private, and access them through properties.
Let me know if you have any more probs.

Dan.

"Haobin" <an*******@discussions.microsoft.com> wrote in message
news:04**********************************@microsof t.com...
Hi everyone,
I have an ArrayList whose members are classes. These classes are
derived from a same base class. The base class has a floating point array and a
string. How do I access each element in the floating point array in a

member
of the ArrayList?
Any help would be greatly appreciated.

Haobin


Nov 16 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: theo | last post by:
Program flow...load file,then extract the xml text tags from the file,then the number of Xml tags retrieved from the file determines the number of dropdownlist controls instanciated in the...
3
by: S | last post by:
Hi there, Here's a question for ya: I'm serializing something that looks like this: Class Widget --> My base class public ArrayList TextGroups --> An...
14
by: Mike | last post by:
I had a question about threading and access to private class variables. I am developing a windows service which has a class inside of it which will receive various asynchronous calls to it via...
9
by: Steve | last post by:
Hello, I created a structure ABC and an array of type ABC Public Structure ABC Dim str1 As String Dim int1 As Integer End Structure Public ABC1 As New ABC, ABC2 As New ABC
24
by: RyanTaylor | last post by:
I have a final coming up later this week in my beginning Java class and my prof has decided to give us possible Javascript code we may have to write. Problem is, we didn't really cover JS and what...
9
by: gk245 | last post by:
I have something like this: struct block { int x; int y; float z; }
7
by: Adam Honek | last post by:
Is there a direct way to remove one entry from a one dimensional array? I keep looking but either my eyes are funny or it isn't there. Must we really create a temp array and copy all but 1 of...
9
by: Brian Tkatch | last post by:
I'm looking for a simple way to unique an array of strings. I came up with this. Does it make sense? Am i missing anything? (Testing seems to show it to work.) Public Function Unique(ByVal...
6
by: Urs Thuermann | last post by:
With offsetof() I can get the offset of a member in a struct. AFAICS, it is portable and clean to use this offset to access that member. I need to do something like this struct foo { struct...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.