Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A List of varying types?

Id' like to create a list of data that will be passed from method to method, however I can't use a struct because the data that will be contained in this list will vary depending on the input.

For example

if (x == 1) {
   a = 1 
   b = true   
   c = 42
   d = "hello"
}

if (x == 2) {
   a = 2
   b = 'g'
   c = "sup"
}

I believe my options are thus:

  1. Create an array or List of strings, and cast the data back to what it originally was from strings. This is messy and could lead to bugs of uninterpretable input, though wouldn't be so bad since it'd all be detected at runtime.
  2. Create a struct for each possibility - Is this even good practice?
  3. Somehow use generics. From what I know, while generics are type-safe yet not type-strict, they must be cast to types before being used. Eg if I wanted a List of items here, I'd need to cast them to strings much like would happen with solution 1, making this useless.

My question then, is which of these options is the best? Or is there an alternate option using some sort of generic type I don't know about? The number of possible variables in each case may change, as with their types. I'd like to be able to return a single List or Array to the calling method, so that it may appropriately deal with the result. It will know how to deal with each group of data based on the value of a, as it will be the 'action choice' identifier. I'm also aware that casting them to objects and back each time is very intensive so I'd rather avoid that.

This is probably pretty simple but it has me stumped...

like image 687
George Avatar asked Dec 18 '22 06:12

George


1 Answers

Since you don't know before hand what the list will contain, it looks like a good case for using an ArrayList.

If you want to get back to the values using a key, consider using a Hashtable.

like image 91
Alfred Myers Avatar answered Jan 03 '23 01:01

Alfred Myers