Let's say I have an array I need to store string values as well as double values. I know I can store the doubles as strings, and just deal with the conversions, but is it possible to use an array with two data types?
No, we cannot store multiple datatype in an Array, we can store similar datatype only in an Array.
Array is a derived data type which is used to store the data of the same type in a contiguous memory location. We can store any type of data types ranging from int , float, double, char to pointer, string, structure.
You can use a Map data structure instead of an array. This is basically a type of Collection that has key-value pairs. Your string name can be used as the key and the value is your integer. Map<String,Integer> myMap = new HashMap<String, Integer>; MyMap.
The values in an array can be any type, so that arrays may contain values that are simple reals or integers, vectors, matrices, or other arrays. Arrays are the only way to store sequences of integers, and some functions in Stan, such as discrete distributions, require integer arguments.
You may use object[]
and do some type checking. You will get some boxing/unboxing when accessing the doubles, but that will be faster than double.Parse()
anyway.
An alternative is to create a class with both types and a marker:
class StringOrDouble
{
private double d;
private string s;
private bool isString;
StringOrDouble(double d)
{
this.d = d;
isString = false;
}
StringOrDouble(string s)
{
this.s = s;
isString = true;
}
double D
{
get
{
if (isString)
throw new InvalidOperationException("this is a string");
return d;
}
}
string S
{
get
{
if (!isString)
throw new InvalidOperationException("this is a double");
return s;
}
}
bool IsString { get { return isString; } }
}
and then create an array of StringOrDouble. This will save you from some typechecking and boxing, but will have a larger memory overhead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With