1

I'm trying to make a hash function using the Cuckoo Hash method. The problem comes when I want to store my table in a 2d array, each column represent one type of hash function and it's index. When I tried to make it more general, I also run into the problem of making the table itself general type. However I cannot find anything that allow me to do so.

I've tried to use the method mentioned here : How to create a generic array in Java? but due to my lack of knowledge I can't get it to work by creating a new Class. I've tried to use Object arrays also, and it works until I need to get data from it and it just refuse to let me cast it to Node unless I wrap it inside a function. That way became messy and full of potential bugs

class CuckooHash<Key, Node> {
    class Node{ // Node of a hash to store  key and value
        Key key ;
        Value value ;
    }
    int capacity ;
    Node[][] table = (Node[][]) Array.instanceOf(new Class<Node[]>, capacity ) ; // I tried to mimic C  dynamic array base on what I was able to grapsh
    table = (Node []) Array.instanceOf(new Class<Node>, capacity) ;

Basically, what I want is for table to be a 2d array with general type and to do it in a comprehensive, cleanest way possible. On a side note I do know that ArrayList is available but for my purposes this is what I'm stuck with

marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388

1 Answers1

0

Don't reuse names; now both your generics param is called 'Node' as well as an inner class. Secondly, stick with java idioms: generics params should be a single capital letter. try 'N'.

You can't make arrays of parameters. Generally, you just use 'Object' (this is what ArrayList does).

The trick you linked to is that the caller passes in a Class reference representing the type of Node, but you haven't added that as a parameter, and generally you don't want to do that. For example, That then means trying to take List<String> as node is not possible.

I'm 99% certain you just want Object[][] here. Cast to (T) everywhere it is necessary and don't grant access to this field via a (public) accessor, and you still have type safety.

rzwitserloot
  • 44,252
  • 4
  • 27
  • 37
  • Would you suggest on how to cast it so I don't have to write a wrapper function. I tried (Type) but it doesn't work for whatever reason. I think Im missing something here, but the only way I got it working is through a function returning the Object in Node type, also Im new and are not experienced in Java, thus my abomination of a class, I will try to improve, with your advise – Thanh Sơn Trần Feb 07 '19 at 17:35
  • public class MyArrayList { Object[] elems; public E get(int idx) {return (E) elems[i]; } this works fine, though you'll have to suppress an unsafe cast warning on the get method. – rzwitserloot Feb 08 '19 at 13:15
  • I was hoping for a way which I don't have to use a function at all though – Thanh Sơn Trần Feb 09 '19 at 07:13