Is it possible to have an array that contains two different types of data? I want to have an array that contains a double and also a string. I attempted:
ArrayList<double><String> array;
But that didn’t work.
Sorry for the silly question, but it has been a while since I have used something like this.. Can you refresh my memory on how would I declare and populate such an array?
And then to take it a step further, I would like to sort the array by the double if possible?
Thanks!
Firstly, it’s worth being clear about the difference between an array and an
ArrayList– they’re not the same thing at all.However, in either case you can’t do what you want. The closest you can probably come is declaring your own type. (EDIT: My original code had a double or a string… I’ve now changed it to be a double and a string. Let me know if this change isn’t what you had in mind.)
Then create an
ArrayList<DoubleAndString>or aDoubleAndString[].Now, this feels somewhat vanilla at the moment – presumably the double and string values actually have a greater meaning – a name and a score, for example. If so, encapsulate that in a type which describes the pairing more appropriately.
As for ordering – you could make
DoubleAndStringimplementComparable<DoubleAndString>– but unless that’s the only natural ordering which makes sense, I’d write aComparator<DoubleAndString>:Then you can use
Collections.sortto sort anArrayList<DoubleAndString>orArrays.sortto sort an array.