I am trying to write the Data Structure for a Hash Table using Chaining. When i remove the keyword "static" from the nested class, i get the error that "Cannot create a generic array of SeparateChaining.Node"? on the line where i allocate memory to hmap using new.
With the static keyword it works fine.Can anybody please point out the significance of the keyword static here and the difference it makes? I am creating an array of object, then how come it shows generic array in the error (Eclipse)?
public class SeparateChaining<Key,Value> {
private int m;
private Node[] hmap;
private int n;
public SeparateChaining()
{
m=5;
n=0;
//error here on removal of static keyword from the node class declaration
hmap=new Node[m];
}
private ____ class Node //works fine with static. Otherwise shows error
{
private Object key;
private Object value;
private Node next;
public Node(Object k, Object v)
{
key=k;
value=v;
}
}
Thanks
static nested class : Nested classes that are declared static are called static nested classes. inner class : An inner class is a non-static nested class. Attention reader!
Thus in above example, class NestedClass does not exist independently of class OuterClass. A nested class has access to the members, including private members, of the class in which it is nested. However, the reverse is not true i.e., the enclosing class does not have access to the members of the nested class.
Can we declare a class as static in Java? Java doesn't allow you to create top-level classes as static. You can only make a nested class as static . By doing so, you can use the nested class without having an instance of the outer class.
From the above points, we can say Java's creators had not allowed an outer class to be static because there is no need to make it static. Allowing to make the outer class static will only increase complications, ambiguity, and duplicity.
If you declare the inner Node
class as static
, then the class is associated with the outer class SeparateChaining
. Node
is then in fact SeparateChaining.Node
.
Without the static
, it will be associated with an instance of SeparateChaining
, which will need a couple type parameters, thus the inner Node
class will also need those type parameters. Node
is then in fact SeparateChaining<Key, Value>.Node
; and in Java, creating an array of generics is not legal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With