class declaration and definition in Java - java

public class Tree<T>
{
private Node<T> root;
public Tree(T rootData)
{
root = new Node<T>();
root.data = rootData;
root.children = new ArrayList<Node<T>>();
}
}
I found a code in which the class is declared like this? What does mean?

The class is for a Tree, which is a common data structure used to store things in a tree like form (each part of the tree is called a "node", and then each node can have a child node to its left or right like this.
The generic parameter T means we can create a tree of any type, and all the nodes in that tree will need to be of that same type.
The constructor we see allows us to create a new Node (the top of the tree), initialise it with the rootData, and create a list of children which will be all of the nodes below this root node.

This is a generic. When instantiating a Tree you can provide a class such as Tree<String> that will be used for the Node in a similar way, and as the constructor parameter type.

Related

Java member function for BST in order traversal

I recently was in a interview and was asked to code a in order traversal for a BST using the java member function prototype below.
public void inOrderPrint()
I was confused by the fact that it did not take in any parameters. I am used to the node to be passed in. It is very easy to traverse the tree with the node passed in... I am just a little confused how one would go about it without the initial reference?
The given signature makes sense if inOrderPrint() is defined in the Node class of the BST, then it's implied that the tree to traverse is the one rooted in the current node. Alternatively, it could be that the tree is an attribute in the current class. Assuming that the method is in the node class, it'd be something like this - and do notice how the recursion gets called:
public class Node {
private Node left;
private Node right;
private Object value;
public void inOrderPrint() {
if (left != null)
left.inOrderPrint();
System.out.println(value);
if (right != null)
right.inOrderPrint();
}
}
Given that it's a member function,one can assume that you have access to the root (e.g. this.root). You could just overload this method with a method where you pass in a node. You would then call the overloaded method inside the given one with the root.
EDIT:
I thought the method was defined in the tree, not in the Node class. You could do it like this: (make sure to check for null!)
public void inOrderPrint(){
//traverse down the left tree
this.left.inOrderPrint();
System.out.println(this);
//traverse down the right tree
this.right.inOrderPrint();
}

Java Programing Data field "head"

Im in a Java class at school and for the next program we have to edit a list. However there is one part of the instructions I don't understand.
Instructions from Homework:
It has a single data field "head" with the data type of MyNode, which is defined as follows:
public class MyNode<E extends Comparable<E>> {
E element;
MyNode<E> next;
public MyNode(E item) {
element = item;
next = null;
}
}
It contains a non-argument constructor that initialize head to be null.
I don't understand what my instructor means by "head"? Is he referring to the list as the "head"? Any ideas will help. Thank you.
That looks like the implementation of a linked list where each item (or node) contains a link to the next item (or node). Often the first item in a linked list is referred to as the 'head'.
So the instructions are asking you to write a class that contains a variable of type MyNode called head.
Something like this:
public class MyAnswer {
private MyNode head;
public MyAnswer() {
head = null;
}
}
In a linked list, head is the first element or node in the list. The head serves as an entry point to your list as you can reach any element (let's say the nth element) of the list by starting from head and accessing the next field of the node objects n times.

Using an Interface in Java

Well I have a fairly simple question I just can't seem to find my way around...
For a class, I have to implement an interface for a binary tree that has a method like:
public List<Node<E>> listAll();
we are required to have a class called MyNode.java, which is what I use to make my tree with. So to list all children I thought I would do this:
public List<Node<E>> listAll(){
List<Node<E>> childList = new ArrayList<>();
MyNode<E> thisNode = this.l;
while(thisNode!= null){
childList.add(thisNode);
thisNode = thisNode.l;
}
return childList;
}
and to do something like set a child
public void setChild(Node<E> child){
E elem = child.getElement();
MyNode<E> newNode = new MyNode(elem);
this.l = newNode;
}
So my question is: am I going about this correctly? If I try to create a Node, I can't because my nodes are called MyNodes but when I try to create a list of MyNodes and return them it gives me an error because I am not following the interface.. When I try to make the method accept MyNode instead of Node it says I am not following the interface. A little more clarification below..
I currently am using the implements declaration to implement the Node.java interface.. When I am writing the method that is specified by my interface as:
public void setChild(Node<E> child);
then I am currently fleshing out the method like so:
public void setChild(Node<E> child) {
E elem = child.getElement();
MyNode<E> newNode = new MyNode<E>(elem);
MyNode<E> transNode = this.l;
if(transNode!=null){
while(transNode.r!=null){
transNode = transNode.r;
}
transNode = newNode;
}
else transNode = newNode;
}
you can see how I am getting the element from input child and creating a new MyNode out of it to put as the new child instead of just injecting Node into my tree.. Is this wrong? I can't seem to get another way to work...
Interfaces are good for making code generic. If you wanted to have multiple implementations of a Node class that each would have the same methods then making an interface would be a good idea.
Alternatively, if you want to enforce an API for someone else to use, and interface is the right way to do that. You can make methods that accept any object that implements that interface.
If you're just creating one Node class for a simple binary tree implementation it might not make sense. Your binary tree might want to implement a Collection interface to make it available as a generic structure.
If you want to contractualize yourself to an API before beginning, an interface could further be a good way to do that.
In general you don't want to create an interface unless you want an abstraction where you actually will write different implementations of that abstraction. In your case, class Node<T> will suffice for your needs.
It is generally considered good form to use an interface for the API.
Briefly, doing so:
allowing the caller to provide whatever implementation they like
makes testing easier, especially when using mocks
chisels the least amount of the API in stone
See Liskov substitution principle

doublylinkedlist creating node

I am working on a assignment in java that uses a generic type doubly linked lists. I'm sure this is a basic question but since I could not find the answer I thought I would ask. Essentially the implementation of the doubly linked list class is given and all I am required to do is create some nodes. The problem I am having is that the node class is a private static nested class in the list class and I do not understand how I should be using it. The list class looks something like this (leaving out several get and set methods):
public class LinkedList<E> {
private static class Node<E>{
private E element;
private Node<E> previous;
private Node<E> next;
public Node(E e, Node<E> p, Node<E> n) {
element = e;
prev = p;
next = n;
}
}
}
In my driver class I use this:
LinkedList <String> linkedlist = new LinkedList<String>();
LinkedList.Node node = linkedlist.new Node();
node n1 = new node("Amy", null, null);
Using this I get an error saying that LinkedList.Node should be changed to default visibility. Any help is appreciated.
As mentioned by #Lonenebula you don't want to access the Node class from outside of the LinkedList class.
To use the LinkedList, you don't create the node itself, but rather just add the element to the list. The internal code of the LinkedList class will hold all the required details on how to create a new node.
For example to add an element to the List you would have an add(E e) method. This method will then contain the logic to create the node and add it to the List. Within your list class you should already have the next and previous Nodes or have the logic to tell if it is the first or last Node.
At no point should you need to access the Node class from outside of the LinkedList class.

Tree that sorts classes hierarchicly

I need a tree-structure that sorts all added classes hierarchically. I have to get all classes that inherit one certain class. That one particular read access needs to be very fast.
Example:
I add the following classes.
public static class Event
{
}
public static class PlayerEvent extends Event
{
}
public static class PlayerMoveEvent extends PlayerEvent
{
}
public static class WorldEvent extends Event
{
}
It should sort the classes like this:
http://i.imgur.com/J6DyZvL.png
Use a Map <Class, List <Class>>, where the key is the parent class, and the List contains all the children.
Have a Node class that represents a node in your tree.
It stores the class that it represents and its direct children.
class Node {
Set<Node> children;
Class class;
}
Then you can construct the tree, and get your root node.
List<Class> classList = ...l
Map<Class,Node> classMap = ... a map from all your classes to nodes made from them;
Node rootNode = null;
for(Class c : classList){
Node parentNode = classMap.get(c.getSuperclass());
if(parentNode != null)
parentNode.children.add(classMap.get(c));
else
rootNode = classMap.get(c);
}
Andres answer is best for O(1) lookup.
You always have to iterate if you are using a hierarchial data structure . If you want to store the hierarchial data structure so that you can have O(1) retrieval , you need to have memory to snapshot it. Java stores references , so it wont be as much memory as you are thinking of, but it still would not be insignificant. If you want to save on memory you can use disk sapce by writing the values of the child classes to a file . Every time you add a child class, you append a row to the list of child classes.

Categories