Set a fixed size ArrayList - arrays

someone knows if it's possible create a fixed size ArrayList? Or I have to use necessarily an array?
I try with this
Dim array As ArrayList
array = New ArrayList(10)
and
array.Capacity = 10
But I can add more than 10 items, and it doesn 't show me any kind of error how I expected.
Thanks

Just use an Array this size will not change unless you explicitly code it to.
Dim myArray(9) As String 'or whatever object you need Integer, etc.
Note that specifying 9 will create 0-9 i.e. 10 items in your array
(ArrayLists are bad in many many ways so don't use them)

Capacity of ArrayList tells the maximum number of items ArrayList can currently hold. Capacity will be increased automatically at run time when more items are added in the ArrayList.
For fixed size, use Array as mentioned below:
Dim intArray(9) As Integer

If you are wanting to store different types in your collection you can use;
Dim myArray(5) As Object
If you wanted to read them back as the type you put them in as you would have to convert their type back what they were originally.
I do not recommend this as an approach. If you want to do this then I suggest you create a custom object such as a class or structures that will contain properties for each of the values you wish to set.

Related

Array variable is used before assigned a value

When I rebuild the solution I get the warning:
"Variable 'aMyArray' is used before it has been assigned a value."
A function in VB.NET uses an array which is dynamically populated.
Example:
Function MyArray()
Try
Dim aMyArray()
For i = 0 to 100
ReDim Preserve aMyArray(i)
Next
Catch ex As Exception
End Try
End Function
How should I declare a dynamically populated array to eliminate this warning?
I like to use the CreateInstance to avoid possible errors:
Dim aMyArray() as string = Array.CreateInstance(GetType(String),0)
A. Your function returns nothing, so you should also have a warning about that
B. You seriously need to turn on Option Strict and let the compiler point out other errors like aMyArray has no Type.
C. Never use and empty Try/Catch; if there is an exception, you want to know when something goes wrong (and where) so you can fix it.
D. Avoid arrays like the plague. ReDim Preserve aMyArray(i) creates a new array and then copies all the data to the new structure. This can be costly in terms of performance if it is a large array of something like strings. Net has several very nice collections such as List(of T) which do not need to be explicitly resized:
Private myList As New List(of String) ' or Integer, Decimal or even MyClassObject
...
myList.Add("Hello")
myList.Add("Lists...")
myList.Add("Goodbye")
myList.Add("Arrays")
D(1). The result of using a List would mean that entire procedure can be done away with. Just add new things to the list as needed.
E. The code posted cant actually result in the warning because you dont ever add a value to it. Adding: aMyArray(2) = 2 after the loop will result in the warning. This is because you have never fully declared the array (size and type) as in:
Dim aMyArray(100) As String
ReDim simply resizes the array which isnt the same thing.
F. Since there is nothing in your new array, there is no reason to use ReDim Preserve because there is nothing to preserve. I'll assume that is supposed to be some calculation. On the other hand, if you are trying to resize an existing array, it should be a Sub.
We are all left to guess if it really is meant to modify an existing array (based on ReDim Preserve) or return a new array of stuff (considering the array is declared in the procedure).
Again, none of this is needed using a List, Dictionary or other Collection Type.

In order to preallocate memory in Matlab, I want to initialize my array of objects. How do I do this?

I have a class of objects known as blocks. Currently, I am creating an array of blocks using a for loop by simply tacking them unto an empty array
blockArray=[];
for ii=1:Size
blockArray=[blockArray block(....)];
end
In order to preallocate memory, how do I initialize an object array of blocks with dummy values?
For instance if instead of using block objects I used numbers, I could easily preallocate by using zeros(1,Size). Is there something similar that I could do?
The matlab documentation describes
To preallocate the object array, assign the last element of the array first. MATLABĀ® fills the first to penultimate array elements with default DocArrayExample objects.
So, to do this, instead of iterating over from 1:size, it is simpler to do...
blockArray = []
blockArray(size) = block(...)
The language does not really support this, there exists multiple solutions (or workarounds).
Replicating the first instance
When pushing the first element into the array, you can fill the whole array with this element to achieve a preallocation. This might look very bad, but it is actually the fastest possibility known to me.
for ii=1:S
%assumption e is a scalar, otherwise the code is totally screwed
e=block(....)
if ii==1
%to do preallocation, fill it with your first element
blockArray(1:S)=e
else
blockArray(ii)=e
end
end
Use cell arrays
Obvious simple solution, you can put any class into the fields
blockArray=cell(S,1);
for ii=1:S
%assumption e is a scalar, otherwise the code is totally screwed
e=block(....)
blockArray{ii}=e
end
This solution is very simple but slower than the first. You also lose some functionality which is not available for cell arras
Let your class implement array functionality
classdef A
properties
arg1
out
end
methods
function obj = A(varargin)
if nargin==0
%null object constructor
elseif strcmpi(varargin{1},'createarray')
sz=varargin(2:end);
%preallocate
obj(sz{:})=A;
else
%standard constructor
obj.arg1=varargin{1};
obj.out=[1 2 3;];
end
end
end
end
Constructor with no input argument creates an "empty" or "null" object, this is used to preallocate so it should be empty.
Constructor with first parameter makearray creates an array
Otherwise your constructor should be called.
Usage:
%create an empty object
A
%create an array of size 2,3,4
A('createarray',2,3,4)
%use the standard constructor
A(2)
Biggest downside is you have to modify your classes. Never tested this solution, but it should be close to the first in performance.

How to find out length of an array in VBA? Ubound does not give actual length.

I basically want to write logic such that if certain element is already present in array i dont want to again put it into it. My array is one dimensional. I am not able to understand how filter function works. Please help. Thanks.
I'm not sure I exactly get what you are trying to do.
But what I understand makes me recommend you to use Dictionary (it is basically a Hashmap)
It works with keys and values.
Each element of this Dictionary contains a unique key (a String that is used to access specifically the data you want) and a value attached to it (can be a String, a Number...)
Here is how to use it :
in your VBA page, go to Tools -> References -> add "Microsoft Scripting Runtime" from the list of available references.
Then in your code :
Dim myDico as Dictionary
set myDico = new Dictionary
myDico.add "myKey", 5
msgbox myDico.Item("myKey") '5

Qt integer array model

For instance, to represent a QStringList int GUI listview we just create a QStringListModel and bound it to the GUI. example here.
In my case i have a file filled with integers, what i whant to do is parse the file into my memory for instance in integer array so i could work with data. Now, how do i bound this data to my gui, and if integer array is not apropriate, what kind of data structure should i choose?
int array[3] = {1,3,2};
model = new Q***Model(this);
model->set***(array);
To bound custom data to a view you need QStandardItemModel along QStandardItem, using that combination should also eliminate the need to use an array to store your file input.
QStandardModelItem
You Can Simply Convert the integers to string, Create a Qlist of Standard item model Using the Strings gotten from the integer . Assign to each Standard item its integer data; Than append the standard item to the qlist. Check http://doc.qt.digia.com/qt/qstandarditem.html#setdata
several ways to Convert to string http://www.qtforum.org/article/24878/convert-int-to-qstring.html

Using My.Settings to save an array

How do you save an array or an ArrayList in VB.NET using My.Settings? I cannot find the array type anywhere, even in the browse window.
I know I can convert the array to a string, but I do not know how to convert a string to an array. I know that if I were to break it at a delimiter then I could convert a string to an array, but my problem is that any text at all could be stored within the array as a single value, so I cannot pick a delimiter that is unlikely to be used.
I was also facing the same problem and I came up with a solution to this.
Here are the steps:
Open up the properties of your app and select settings
select the setting name and then where it says type click on the
arrow and select browse.
in the browse window type in system.collections.arraylist and hit enter!
there you have your array!
You can use array like this:
your_array_name(here_comes_the_item_no.) = whatever
What kind of array? I've had luck using StringCollection for strings. ArrayList works for most anything else (and that's about the only place I'd use arraylist).
I would either use the StringCollection type, and just convert your elements to/from strings when storing them in my.settings, or use XML Serialization to turn the array in to an xml string, and store that in my.settings.

Resources