Christian
Christian

Reputation: 26387

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];

but that doesn't seem to work.

Is Entry the right datatype to use?

Upvotes: 2

Views: 10191

Answers (5)

bragboy
bragboy

Reputation: 35542

Use this,

List<Entry<String, Integer>> li = new ArrayList<Entry<String, Integer>>(); 

Upvotes: 1

fish
fish

Reputation: 1050

Maybe you can just use ArrayList, shouldn't be much difference in performance compared to a plain array.

Upvotes: 1

Martijn Courteaux
Martijn Courteaux

Reputation: 68847

I don't know what is not working, but:

  1. you have to give a name to your array.
  2. you can't construct arrays with generic types
  3. 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!

Upvotes: 1

Joachim Sauer
Joachim Sauer

Reputation: 308011

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).

Upvotes: 3

Sevas
Sevas

Reputation: 4273

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/

Upvotes: 2

Related Questions