473,383 Members | 1,818 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,383 software developers and data experts.

ArrayList problem.

GTi
If I use:

ArrayList TimeScale = new ArrayList();
TimeScale.Capacity = 1000;
TimeScale[20]="test 1"

The last line trow me an error:
Index was out of range. Must be non-negative and less than the size of
the collection.
Parameter name: index

Is there anything I don't get here?

Jan 17 '06 #1
15 1671
ArrayList objects are not arrays - it is (essentially) a collection class;
initially (in general - some ctors allow preloading) they are empty. The
capacity is just the upper limit on what it can contain *without having to
grow*. The Count is the current amount of data. If you call .Add() 5 times,
then you will have 5 items, even if the capacity is 200, and [20] will fail.

Are you sure you mean to use ArrayList? You could create (for example) a
string array sized for 1000 items, and then [20] would work.

Marc
Jan 17 '06 #2
GTi <tu****@gmail.com> wrote:
If I use:

ArrayList TimeScale = new ArrayList();
TimeScale.Capacity = 1000;
TimeScale[20]="test 1"

The last line trow me an error:
Index was out of range. Must be non-negative and less than the size of
the collection.
Parameter name: index

Is there anything I don't get here?


Yes - the capacity isn't the same as the size. The capacity is how big
the ArrayList can become without having to "grow" by copying all its
data into a bigger backing array.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 17 '06 #3
An ArrayList is a Collection. Use the Add method to add an element to it.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
You can lead a fish to a bicycle,
but it takes a very long time,
and the bicycle has to *want* to change.

"GTi" <tu****@gmail.com> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.com...
If I use:

ArrayList TimeScale = new ArrayList();
TimeScale.Capacity = 1000;
TimeScale[20]="test 1"

The last line trow me an error:
Index was out of range. Must be non-negative and less than the size of
the collection.
Parameter name: index

Is there anything I don't get here?

Jan 17 '06 #4
GTi
NOTE:
This sample was just a example. In this samples I should use .add();
But the a value is any value between 0 and maxitems and not all values
in that range is used.

Jan 17 '06 #5
GTi
(where did the sample go?)

class TimeScale
{
public double TempSP = 0.0;
public double TempER = 0.0;
public double PresureSP = 0.0;
public double PresureER = 0.0;
}
maxitems=1000; // from a calculation
ArrayList TimeScale = new ArrayList(maxitems);

for(int a=0; a<maxitems; a++)
{
TimeScale gts = new GraphTimeScale();
gts.TempSP = somevalue2;
gts.TempER = somevalue3;
gts.PresureSP = somevalue4;
gts.PresureER = somevalue5;
TimeScale[a]=gts;

// NOTE in this sample I should use .add(gts);
but <a> can be any number from 0 to maxitems and not all indexes is
filled.

Jan 17 '06 #6
> GTi <tu****@gmail.com> wrote:
If I use:

ArrayList TimeScale = new ArrayList();
TimeScale.Capacity = 1000;
TimeScale[20]="test 1"
The last line trow me an error:
Index was out of range. Must be non-negative and less than the size
of
the collection.
Parameter name: index
Is there anything I don't get here?

Yes - the capacity isn't the same as the size. The capacity is how big
the ArrayList can become without having to "grow" by copying all its
data into a bigger backing array.


Most of us know that to be true. However, the docs would lead one to believe
it *should* work like the OP expected.

from ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.1033/cpref/html/frlrfSystemCollectionsArrayListClassCapacityTopic. htm

"When the value of Capacity is set explicitly, the internal array is also
reallocated to accommodate the specified capacity."
Jan 17 '06 #7
GTi
One sample I have about 10000 items in a array.
The short discription is like this:

class TimeScale
{
public double TempSP = 0.0;
public double TempER = 0.0;
public double PresureSP = 0.0;
public double PresureER = 0.0;
public int StatusCode = 0;
}

maxitems=1000; // example
ArrayList TimeScale = new ArrayList(maxitems);
for(int a=1; a<maxitems; a++)
{
GraphTimeScale gts = new GraphTimeScale();
gts.TempSP = somevalue1;
gts.TempER = somevalue2;
gts.PresureSP = somevalue3;
gts.PresureER = somevalue4;
gts.StatusCode = somevalue5;
TimeScale[a] = gts;
}
Is there any other and better way of doing this?

Jan 18 '06 #8
chris martin <chris_m|NOSPAM|@caliber|SPAM|web.com> wrote:
Yes - the capacity isn't the same as the size. The capacity is how big
the ArrayList can become without having to "grow" by copying all its
data into a bigger backing array.


Most of us know that to be true. However, the docs would lead one to believe
it *should* work like the OP expected.

from ms-help:<snip>

"When the value of Capacity is set explicitly, the internal array is also
reallocated to accommodate the specified capacity."


That doesn't suggest that it should have worked. That talks about the
size of the internal array, *not* the logical size of the ArrayList
itself.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 18 '06 #9
GTi <tu****@gmail.com> wrote:
One sample I have about 10000 items in a array.
The short discription is like this:

class TimeScale
{
public double TempSP = 0.0;
public double TempER = 0.0;
public double PresureSP = 0.0;
public double PresureER = 0.0;
public int StatusCode = 0;
}

maxitems=1000; // example
ArrayList TimeScale = new ArrayList(maxitems);
for(int a=1; a<maxitems; a++)
{
GraphTimeScale gts = new GraphTimeScale();
gts.TempSP = somevalue1;
gts.TempER = somevalue2;
gts.PresureSP = somevalue3;
gts.PresureER = somevalue4;
gts.StatusCode = somevalue5;
TimeScale[a] = gts;
}
Is there any other and better way of doing this?


Yes - call the Add method instead of using the indexer. Note that that
will fill the ArrayList from index 0 rather than index 1 (you know
you're only adding maxitems-1 items in the above, don't you?).

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 18 '06 #10
GTi <tu****@gmail.com> wrote:

<snip>
// NOTE in this sample I should use .add(gts);
but <a> can be any number from 0 to maxitems and not all indexes is
filled.


In that case I suggest you call Add enough times adding null elements,
then use the indexer to set the specific values you're interested in.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 18 '06 #11
One leaps to mind: use an array!

In your example the required size is obviously fixed at 1000 (well, 999
actually but who's counting), and you aren't using any of the "bouns"
features of the ArrayList, so why not just use an array? i.e.
GraphTimeScale[].

This would have less overhead, and would give you better type safety. Note:
if you are using .Net 2.0, even if you can't use GraphTimeScale[] you might
want to consider replacing ArrayList with List<GraphTimeScale>

Marc
Jan 18 '06 #12
As another thought: you say not all indexes are filled. How sparse is it?
20%? 80%?

If it is going to have any reasonable amount of emptyness, another option is
to use a HashTable, using the index as the key (and will be unique).
Functionally it would be very similar: access might be *slightly* slower
(due to having to look through the hash buckets), but it should still be
acceptable for most usage. If you are using 2.0 you could use
Dictionary<int, GraphTimeScale> which is the generic, type-safe version.

Marc
Jan 18 '06 #13
GTi

Marc Gravell wrote:
As another thought: you say not all indexes are filled. How sparse is it?
20%? 80%?

If it is going to have any reasonable amount of emptyness, another option is
to use a HashTable, using the index as the key (and will be unique).
Functionally it would be very similar: access might be *slightly* slower
(due to having to look through the hash buckets), but it should still be
acceptable for most usage. If you are using 2.0 you could use
Dictionary<int, GraphTimeScale> which is the generic, type-safe version.

Marc


It can have as low as 2 items in a 10000 list :|

I think I must redesign my function using HashTable or Dictionary.

Tx Marc

Jan 18 '06 #14
How about this then:

public class SomeClass { // class for test harness
public readonly int SomeField;
public SomeClass(int value) { SomeField = value; }
}
public class SparseArray<T> { // impersonates an array, but hashtable
implementation
private Dictionary<int, T> data;
public SparseArray() {
data = new Dictionary<int, T>();
}
public SparseArray(int capacity) {
data = new Dictionary<int, T>(capacity);
}
public IEnumerable<int> Indexes {
get { return data.Keys; }
}
public IEnumerable<T> Values {
get { return data.Values; }
}
public void RemoveAt(int index) {
data.Remove(index);
}
public T this[int index] {
set { data[index] = value; }
get {
T value;
data.TryGetValue(index, out value); // ignore ret val
return value;
}
}
}
static class Program { // test harness
[STAThread]
private static void Main() {
Random rand = new Random();
SparseArray<SomeClass> data = new SparseArray<SomeClass>();
// create a sparse "array" in a dictionary
// note that data[i] is **NOT** the position, rather the **key**
(hashtables do not have a strict position)
for (int i = 0; i < 2000; i += rand.Next(1,500)) { // just to
make it interesting
data[i] = new SomeClass(rand.Next());
}

Console.WriteLine("Using indexer (exhaustive)");
for (int i = 0; i < 2000; i++) {
SomeClass value = data[i];
if(value != null)
Console.WriteLine("{0}: {1}",i,value.SomeField);
}

Console.WriteLine("\"In use\" indexes only");
foreach (int i in data.Indexes) {
Console.WriteLine("{0}: {1}", i, data[i].SomeField);
}

Console.WriteLine("Values");
foreach (SomeClass value in data.Values) {
Console.WriteLine(value.SomeField);
}
}

}
Jan 18 '06 #15
Honestly, I don't know why you're using an ArrayList. An ArrayList is a
Collection of type object, which means that one must use casting to cast any
element in the ArrayList to the type that it is. In addition, as a
Collection, it is a variable-length list. If you want a fixed sized list of
the same data type, your best bet is to use an array:

GraphTimeScale[] TimeScale = new GraphTimeScale[1000];

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
You can lead a fish to a bicycle,
but it takes a very long time,
and the bicycle has to *want* to change.

"GTi" <tu****@gmail.com> wrote in message
news:11*********************@z14g2000cwz.googlegro ups.com...
(where did the sample go?)

class TimeScale
{
public double TempSP = 0.0;
public double TempER = 0.0;
public double PresureSP = 0.0;
public double PresureER = 0.0;
}
maxitems=1000; // from a calculation
ArrayList TimeScale = new ArrayList(maxitems);

for(int a=0; a<maxitems; a++)
{
TimeScale gts = new GraphTimeScale();
gts.TempSP = somevalue2;
gts.TempER = somevalue3;
gts.PresureSP = somevalue4;
gts.PresureER = somevalue5;
TimeScale[a]=gts;

// NOTE in this sample I should use .add(gts);
but <a> can be any number from 0 to maxitems and not all indexes is
filled.

Jan 18 '06 #16

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

Similar topics

6
by: Stephen | last post by:
Im trying to carry work out an else if clause in the below method but i'm having a lot of difficulty getting the correct code which allows me to check and see if an arraylist items has text in it...
4
by: Hans De Schrijver | last post by:
I have a private ArrayList variable that holds objects of various types, though they're all derived from a common base class (User). What I would like to do is provide public accessor properties...
3
by: Stephen | last post by:
I was wondering if someone can help me with an web application design problem. I have a aspx page which builds up an arraylist called addresses and outputs the values in the arraylist items to a...
9
by: vbportal | last post by:
Hi, I would like to add BitArrays to an ArrayList and then remove any duplicates - can someone please help me forward. I seem to have (at leaset ;-) )2 problems/lack of understanding (see test...
9
by: Leon | last post by:
I have a webform in which when the user press generate button the form generate six unique ramdon numbers, the user can also type these six numbers in manually in any order. however, the user can...
20
by: Dennis | last post by:
I use the following code for a strongly typed arraylist and it works great. However, I was wondering if this is the proper way to do it. I realize that if I want to implement sorting of the...
0
by: Grant Wickman | last post by:
Our team has just fixed a really nasty problem that appears to be caused by an obscure bug in the sort method of Arraylist and daisy-chained webservice stubs. We've fixed the bug so I'll not...
18
by: Sam | last post by:
Hi All I'm planing to write an application which allows users dynamically add their points (say you can add upto 30,000) and then draw xy graph. Should I use an array for my coordinate point...
48
by: Alex Chudnovsky | last post by:
I have come across with what appears to be a significant performance bug in ..NET 2.0 ArrayList.Sort method when compared with Array.Sort on the same data. Same data on the same CPU gets sorted a...
8
by: amazon | last post by:
I have a following structure that I am using with array list: Private Structure arrayliststruct Public Name As String Public value As String Public type As String End Structure and following...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
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?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.