1

This is a grade 12 java HashTable assignment.

So my teacher gave me the template for doing this assignment, but it does not work :(. And he expects us to get the template to work and then do the assignment.

Here's what he gave us:

class MyHashTable<T>{
    private T[] vals;
    private int load;
    public MyHashTable(){
        load = 0;
        vals = new T[10];
    }
    public MyHashTable(int size){
        load = 0;
        vals = new T[size];
    }
    public void add(T obj){//don't care about negatives
        int size = vals.length;
        if((load+1.0)/size>0.6){
            size*=10;
            T[] tmp = new T[size];
            for(int i=0;i<size/10;i++){
                if(vals[i]!=null){
                    add(vals[i], tmp);
                }
            }
            vals = tmp;
        }
        add(obj, vals);
    }
    public void add(T obj, T[]vals){
        int loc = Math.abs(obj.hashCode())%vals.length;
        while(vals[loc]!=null){
            loc = (loc+1)%vals.length;
        }
        vals[loc] = obj;
    }
    /*public boolean contains(T obj){

    } */
}

it gives an error: error: generic array creation

Can anyone tell me what does that mean? With examples hopefully.

cook cook
  • 195
  • 1
  • 8

3 Answers3

2

Due to the way that generics are implemented in Java, it is not possible to use generics such that type information is needed at runtime. See this.

gparyani
  • 1,872
  • 3
  • 24
  • 35
2

error: generic array creation

You can not create arrays from generic types.

See also What's the reason I can't create generic array types in Java?

Community
  • 1
  • 1
Andreas Fester
  • 34,015
  • 7
  • 86
  • 113
1

As everybody said generic type is erased at runtime:

  • T becomes Object,
  • T extends SomeClass becomes SomeClass.

So you have at least two options

  1. You can use same pattern that was used in ArrayList<T> and store items in Object[] array rather then T[] array

    vals = (T[]) new Object[size];
    
  2. If you want to create array of real T type you would have to make user to pass instance of Class<T> object that will correspond T and use it like

    vals = (T[]) java.lang.reflect.Array.newInstance(clazzT, size); 
    

where clazzT is Class<T> instance.

Pshemo
  • 113,402
  • 22
  • 170
  • 242