Multidimensional array with different types in java
I want to keep a data structure that has a table with one Rows column and another Ints column.
List<Entry<String, Integer>> li = new LinkedList<Entry<String, Integer>>();
will do the job for a list, but I would rather have the performance and consume the array memory.
I tried
Entry<String, Integer>[] = new Entry<String, Integer>[10];
but it doesn't work.
Is Entry the correct datatype to use?
source to share
If you really want an array of generic types, you can do this:
Entry<String, Integer>[] array = new Entry[10];
This gives you a compile warning. You can read about it here:
http://www.devarticles.com/c/a/Java/Wildcards-Arrays-and-Generics-in-Java/2/
source to share
Write a class that represents your tuple and use an array (or list) of that type. Don't avoid classes, they are your friends!
And what exactly do you mean by "array performance"? Arrays are not necessarily faster than List implementations.
Think about inserting an element at position 0: A LinkedList
can do it in O (1). To get the same effect on an array, you need to do an O (n) operation (recreating the array and copying all existing values).
source to share
I don't know what doesn't work, but:
- you need to provide a name for your array.
- you cannot create arrays with generic types
- don't forget
Entry
- this is an interface.
So this:
Entry<String, Integer>[] = new Entry<String, Integer>[10];
Should be:
Entry<String, Integer>[] entries = new Entry[10];
Hope this helps!
source to share