简体   繁体   中英

How to make generic type 2d arrays in Java

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM