For a generic outer class, why do I need to declare a nested class static?

I am trying to write a data structure for a hash table using Chaining. When I remove the keyword "static" from a nested class, I get the error message "Can't create a shared array SeparateChaining.Node"? in the line where I allocate memory for hmap using a new one.

It works fine with the static keyword. Anyone please indicate the value of the static keyword here and the difference it makes? I am creating an array of an object, whereas it shows the general array in 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

+7
source share
3 answers

If you declare the inner class Node as static , then the class is associated with the outer class SeparateChaining . Node then actually SeparateChaining.Node .

Without static it will be associated with a SeparateChaining instance that will need steam type parameters, so the Node inner class will also need these type parameters. Node then actually SeparateChaining<Key, Value>.Node ; and in Java, creating an array of generics is not legal.

+6
source

Well, that’s common. If the inner class is not static, then the type is SeparateChaining<Key,Value>.Node . When you add statics, it is treated like a regular class

0
source

Keyowrd static in the declaration of a nested class means: "I do not want to have a reference to an object of an external class, thank you very much." If you do not put static , then any object of the inner class has a reference to some object of the outer class.

Thus, an object of an internal, non-static class can be created only inside the non-static method of an object of an external class.

-one
source

All Articles