-1

I have a good understanding of data structures and can happily implement them in C++ without issue; I get a little tripped up in Java though due to the generic implementation constraints.

Specifically, I get confused when I'm trying to create a data structure backed by an array. I know, for example, that I cannot do this:

public class HashTable<T> {
    private T[] table;    
    public HashTable() {
        table = new T[10]; //Type param T cannot be instantiated directly.
    }
}

I also know that if I back my generic array list with an object array, I'm going to have to suppress a number of "unchecked cast" warnings which seems of ill form.

What is the best way to create an array-based data structure in Java? Is there some trick that can be used to do it in a cleaner manner than just creating a straight object array and dealing with the messy casting?

John Humphreys
  • 37,047
  • 37
  • 155
  • 255

1 Answers1

0

Instead of using a raw array, use an ArrayList<T>. It's basically a generic wrapper around an array, with a bunch of additional features.

Wyzard
  • 33,849
  • 3
  • 67
  • 87
  • Thank you for the response. Sorry, I think you misunderstood me a little :). I'm asking how you would implement something like array list in the first place. More for theoretical/interview knowledge than for practical use. Array list itself must have addressed this issue; I'm just curious what the best way ended up being. – John Humphreys May 25 '14 at 22:18