Question on Data Structure Design
I plan to design a data struct开发者_JAVA技巧ure including elements as this,
{1, 13, 15, 113, 117, 145}
{2, 23, 27}
{5, 53, 55, 511, 519}
{9, 11}
I have two ideas till now.
1st. Build an Dictionary(Key, Value);
When Key = 1, Value = ArrayList(13, 15, 113, 117, 145)
When Key = 2, Value = ArrayList(23, 27)
When Key = 5, Value = ArrayList(53, 55, 511, 519)
When Key = 9, Value = ArrayList(11)
2nd. Build an ArrayList(SubArrayLists)
subArrayList1 {1, 13, 15, 113, 117, 145}
subArrayList2 {2, 23, 27}
subArrayList3 {5, 53, 55, 511, 519}
subArrayList4 {9, 11}
I plan to access the element when running time. Which solution is better?
Thanks for your comments.
[Updated]
1. Theint
numbers above listed may stand for some objects. like dictionary object, etc.
2. All the data will be load to memory after application launched. Then read only permitted. Not need to write/add/delete etc.How about a Jagged Array ? http://msdn.microsoft.com/en-us/library/2s05feca.aspx
Access to elements via an array index is O(1).
If you are going to do random access then Dictionary will be a good option. But please keep in mind that you need to have unique keys ( since you are going first element of each list as the key first element of each list should be unique )
If you are going to access elements of the data structure sequentially ArrayList is better
It depends on what is more important to you, faster read speeds or faster writes? A Dictionary will give really quick access to stored values but at the same time adding values to dictionary will take longer.
If you have a lot of values that need to be accessed numerous times, then dictionary is the way to go, if you find yourself looping through a list of values inside another for loop example:
foreach(var item in ListA)
{
foreach(var item in ListB)
{
// Match against all values in list B
}
}
In the example above, it'll be best if List B is a dictionary instead of a list since you are looping through the list on every iteration of ListA. As the number of elements in ListB increases the execution time of the above code will increase, however if instead it is a dictionary, it won't make much of a difference.
精彩评论