Multidimensional Array with different types in java
I want to store a data structure thats a table with one column Strings and another column of Ints.
List<Entry<String, Integer>> li = new LinkedList<Entry<String, Integer>>();
would do the job for a list but I would rather have the performance of and need the memory of an array.
I tried
Entry<String, Integer>[] = new Entry<String, Integer>[10];
开发者_StackOverflow社区
but that doesn't seem to work.
Is Entry the right datatype to use?
Write a class that represents your tuple and use an array (or a List) of that type. Don't eschew classes, they are your friends!
And what exactly do you mean by "the performance of an array"? Arrays are not necessarily faster than List implementations.
Think of inserting an element at the position 0: A LinkedList
can do it in O(1). To get the same effect in an array, you'd have to do an O(n) operation (recreating the array and copying all existing values).
If you really need an array of generic types, you can do this:
Entry<String, Integer>[] array = new Entry[10];
It gives you a compilation warning though. You can read more about it here:
http://www.devarticles.com/c/a/Java/Wildcards-Arrays-and-Generics-in-Java/2/
I don't know what is not working, but:
- you have to give a name to your array.
- you can't construct arrays with generic types
- don't forget
Entry
is an interface.
So, this:
Entry<String, Integer>[] = new Entry<String, Integer>[10];
Should be this:
Entry<String, Integer>[] entries = new Entry[10];
Hope this helps!
Maybe you can just use ArrayList, shouldn't be much difference in performance compared to a plain array.
Use this,
List<Entry<String, Integer>> li = new ArrayList<Entry<String, Integer>>();
精彩评论