import java.util.ArrayList;
class Tree<E> {
private class Node<E> {
private ArrayList<Node<E>> list = new ArrayList<Node<E>> ();
private Node<E> parent = null;
private E element = null;
public Node (E e, Node<E> p) {
element = e; // (1)
//this.element = e; <- difference?
parent = p;
}
public Node (E e) {
element = e; // (2)
//this.element = e; <- difference?
}
public void setElement (E e) {
element = e; // (3)
//this.element = element; <- difference?
}
public E getElement () {
return element;
}
public void addChild (E e) {
Node<E> node = new Node<E> (element);
}
public void addParent (Node<E> node) {
parent.addParent(this);
this.parent
}
public void getChildren (Node<E> node) {
}
}
}
So basically, this is my unfinished test project class, and I am really confused what I really should use to pass out the parameter into the variable.
As I indicated in the code, I would like to know the difference between using "this" function and without putting "this" function on the prefix.
For example, in number 1 in the comment, what will happen if I change that to the below comment: this.element?
Also same as in number 2 and 3, am I supposed to use this? instead of just element?
or does this work as same as not using it, no matter what in this case?
In this case it does not change anything. Because your method parameter and class property have different names. The reason for this keyword is to avoid hiding class property by local method property.
This example should explain it:
This will assign method parameter to itself, thus Node.element will not be initialized.
public Node (E element) {
element = element;
}
This will assign method parameter element to Node.element property, thus this property will be initialized.
public Node (E element) {
this.element = element;
}
Number (1) and (2), it makes no difference. When referring to a member variable, you can use this. to make it more explicit.
Number (3), you'll have a problem if you use this.element = element because this is equivalent to doing this.element = this.element, so you never actually assign the parameter to the field.
In this case usage of this has nothing to do with generics.
You only need to use this.element instead of element if you have something which "shadows" your field. For instance:
public void setElement (E element) {
this.element = element;
}
Obviously, you can't write element = element;.
Now to your questions:
public Node (E e, Node<E> p) {
element = e; // (1)
//this.element = e; <- difference?
parent = p;
}
No.
public Node (E e) {
element = e; // (2)
//this.element = e; <- difference?
}
No.
public void setElement (E e) {
element = e; // (3)
//this.element = element; <- difference?
}
Yes. You assign the field to itself, so that would be a bug.
For example, in number 1 in the comment, what will happen if I change that to the below comment: this.element?
Technically nothing different.
Also same as in number 2 and 3, am I supposed to use this? instead of just element?
Technically this makes no difference.
Practically as a matter of style, I prefer always using this when I refer to fields.
Related
I am working on a code that puts new elements on MyStack if they are unique. I had to copy and paste the node starting code, so I'm having a bit of trouble with an issue. I keep getting two error messages, even after trying various workarounds and I'm not really understanding why. I've even tried using some helper functions I've previously made that have worked before so I'm extra confused.
The two errors I consistently get are:
-cannot infer type arguments for MyStack.Node (actual and formal arguments differ in length)
-constructor node cannot be applied to given types. Required, no arguments, found: anything,
Here's my code:
public class MyStack<Anything>
{
private Node first, last;
private class Node<Anything>
{
Anything item;
Node next;
}
public boolean contains(Anything value)
{
for (Node curr = first; curr != null; curr = curr.next)
{
if (value.equals(curr.item)) {
return true;
}
}
return false;
}
public void add(Anything value)
//method that adds a new value to the end of the list
//COMPLETE
{
Node temp = first;
while(temp.next!=null){ //finds the end
temp=temp.next;
}
temp.next=new Node(value, null); //assigns new value
}
public void enqueue(Anything info){
if (this.contains(info)==true) { //if the info is already present
System.out.println("the stack already contains this value");
return;
}
//if we actually need to add the info
if (first == null) { //if there is nothing in the stack
Node temp= first;
first = new Node<>(info,temp);
first = temp;
return;
}
if (first != null) { //if there is already stuff
Node temp = first;
while (temp.next == null)
{ Node newNode= new Node<>(info, temp);
temp.next = newNode;
}
return;
}
}
}
As #Andreas already pointed out, Node needs a constructor.
There are a few other flaws in your Code:
Use Generics
With your Code, you can only store Objects of the class Anything, what strongly limits its reusability. Use a generic instead and you can reuse this class for many more purposes.
Linked List
I suggest, you use the paradigm of a double-linked-list. That way you do not need to find the last Node to add something to the Stack. Node now has a pointer to its previous and next element.
Use the last Object
You have the object last but never use it. To find out, whether the current object is the last one you compare the value to null. This has the effect, that storing a null value will break your List. Instead compare to the Object last, this object is unique and guarantees you, that you are at the end of the list. Both first and last are Nodes that do not contain a value and are simply used to mark the start/end of your List.
Adding elements
Using the changes above, the code in the Method enqueue(T value) becomes significantly simpler: You just check whether contains(value) and decide whether you add the value to the List or not.
All these changes applied result in following code:
public class MyStack<T extends Object> {
private Node first, last;
public MyStack() {
first = new Node(null, null, null);
last = new Node(null, null, first);
first.next = last;
}
private class Node {
T item;
Node next;
Node previous;
public Node(T item, Node next, Node previous) {
this.item = item;
this.next = next;
this.previous = previous;
}
}
public boolean contains(T value) {
for (Node curr = first.next; curr != last; curr = curr.next) {
if (value.equals(curr.item)) {
return true;
}
}
return false;
}
/**
* method that adds a new value to the end of the list
*/
public void add(T value)
{
Node secondLast = last.previous;
Node added = new Node(value, last, secondLast);
secondLast.next = added;
last.previous = added;
}
/**
* only adds value if it is not already contained by the Stack
*/
public void enqueue(T value) {
if (this.contains(value) == true) { // if the info is already present
System.out.println("the stack already contains this value");
}
else {
add(value);
}
}
public static void main(String[] args) {
MyStack<String> test = new MyStack<>();
test.add("foo");
test.add("bar");
test.add("baz");
System.out.println(test.contains("bar"));
System.out.println(test.contains("new"));
test.enqueue("baz");
test.enqueue("MyStack");
}
}
Naming
As you may have noticed, in my explanation I called this class a List. This is because it fulfills more of the characteristics of a List. A Stack usually only provides the methods push to put something at the top of the Stack and pop to remove and return the topmost Object. Optionally peek can return the topmost Object, without removing it from the Stack.
Also consider renaming the method enqueue: enqueue is used in Queues (obviously) and Queues do not forbid to add two equal Objects. So the name is misleading. I would call this method something like addIfNotContaining.
In my Opinion you should name this class to be a List and add a method get(int i) to get a specific element at a position. Naturally adding some other methods like size ect. to comply with a standard List. But I assume you already had, but did not post them because they are not related to your problem.
Multithreading
This Class is far from threadsave. But I let you figure out yourself how to make it threadsave if needed.
I am calling a constructor in a method to insert new nodes.While I am adding new node default constructor is creating new node with default values . I want to just insert values using insert method as in below code . Is there any way I may avoid first node being default.
class Node {
Node right, left;
int data = 0;
Node() {
}
Node(int data) {
this.data = data;
}
public void insert(int value) {
if (value <= data) {
if (left == null) {
left = new Node(value);
} else {
left.insert(value);
}
} else {
if (right == null) {
right = new Node(value);
} else {
right.insert(value);
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Node new_node=new Node();//creating first node with 0 value
new_node.insert(5);
new_node.insert(4);
new_node.insert(9);
new_node.insert(23);
new_node.insert(70);
new_node.display();
}
}
You could use the first value as the first element:
Node new_node = new Node(5); // create 1st node with 1st value
Or you could define a new default constructor with a value that you don't expect to be in the list (let's say -1), but you'd have to be careful about this element in your list that is not really part of the list, and that makes implementing other operations trickier:
Node() { data = -1; }
But all this is symptom of a bigger problem: you shouldn't handle the head of your list in the Node class. It'd be better to create a new class, let's call it MyList and define a Node head attribute on it, and all insert/update/delete/search operations should be implemented on that class.
It's important to keep the head separate, because there will be operations that modify the head. For example, your insert() method doesn't consider the case when the node to insert should go at the beginning of the existing list.
I need help setting up this constructor for my Iterator class. The directions are as follows:
The constructor should create a new stack and push its node parameter onto it, followed by
all left children accessible from the parameter. Consider a case in which the tree consists
only of left children (essentially a linked list). The node with the highest value (root) would
be pushed first and be on the bottom of the stack, followed by its left child just above it in the
stack, followed by its left child, and so on until the leaf, which would contain the lowest value
in the tree. When popping nodes from the stack, they would contain values from lowest to
highest… an in-order traversal.
I am not sure how to create a new stack with the node in the parameter being a type BSTNode type.
Here is my code:
public static class Iterator<E>
{
private Stack<BSTNode<E>> stack;
public Iterator(BSTNode<E> node)
{
}
public boolean hasNext()
{
if(stack.peek() != null)
{
return true;
}
else
{
return false;
}
}
public E next()
{
stack.pop();
E value;
value = (E) stack.pop();
return value;
}
}
As of right now, just ignore the other two methods, I just need help with the Iterator method. I'll figure those out later. Thank you.
I found out my problem was in a different class and method. I set it up as this and I want to know if this is the correct way of doing it.
The instructions for this method is
to create and return an instance of the static nested Iterator class that will be used to iterate through the elements in the tree. The tree's root should initially be passed to the iterator constructor.
Here is the following code I did for that method:
public Iterator<E> iterator()
{
return new Iterator<>(root);
}
root is the top of the binary search tree. It is in that class as a private variable.
Here's how I set it up.
This is just the public that is above the class. Not inside the class. I just return a new Iterator with root being the top value.
public Iterator<E> iterator()
{
return new Iterator<>(root);
}
Then inside the class below it, I create a new stack and have that stack push the nodes and the nodes to the left of it as long as it isn't null.
public static class Iterator<E>
{
private Stack<BSTNode<E>> stack;
public Iterator(BSTNode<E> node)
{
this.stack = new Stack<>();
while (node != null)
{
stack.push(node);
node = node.left;
}
}
public boolean hasNext()
{
return !stack.isEmpty();
}
public E next()
{
BSTNode<E> goodDays = stack.pop();
E result = goodDays.data;
if (goodDays.right != null)
{
goodDays = goodDays.right;
while (goodDays != null)
{
stack.push(goodDays);
goodDays = goodDays.left;
}
}
return result;
}
}
I have a linked list I'm given and I need to find the first value in the list via a getFirst method.I need to display an error message and quit the program if the value is null. The linked list is already given to me link so:
class MyLinkedList
{
private class Node // inner class
{
private Node link;
private int x;
}
//----------------------------------
private Node first = null; // initial value is null
//----------------------------------
public void addFirst(int d)
{
Node newNode = new Node(); // create new node
newNode.x = d; // init data field in new node
newNode.link = first; // new node points to first node
first = newNode; // first now points to new node
}
//----------------------------------
public void traverse()
{
Node p = first;
while (p != null) // do loop until p goes null
{
System.out.println(p.x); // display data
p = p.link; // move p to next node
}
}
}
//==============================================
class TestMyLinkedList
{
public static void main(String[] args)
{
MyLinkedList list = new MyLinkedList();
list.addFirst(1);
list.addFirst(2);
list.addFirst(3);
System.out.println("Numbers on list");
list.traverse();
}
}
Here's what I tried out for the method:
public static Node getFirst(Node list)
{
if (list == null)
{
System.out.println("Error!");
System.exit(1);
}
return MyLinkedList.first;
}
I know this isn't exactly right, we just started this in my class so I'm having trouble understanding what's going on with it. Thank you!
I think you should look at https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html and get an idea for the behavior of a linked list initially. Once you have an idea on how it behaves, you can think about how to add functionality around it. Right now you just have a single method which you call more than you should. What also might help is to create an interface and document it so you know what each method should do.
You should check that first isn't null in order to do what you describe in the question. Also, it is kind of weird that the first node autoreferences itself because usually it is left in null until you add another node
notice that the first value is linked to the first Node with is null. Then you have to check two things
Node == null (you got this)
Node.next == null (you have to do this)
When Node.next == null. It means that Node is first value because it is linked to the initial Node with is null.
Then you have
public static Node getFirst(Node list)
{
// if the list is empty
if (list == null)
{
System.out.println("Error!");
System.exit(1);
} else if(list.link == null) {
// this is the first value!
return list;
} else {
// keep searching recursive with the next Node
return getFirst(list.link);
}
}
The class MyLinkedList in your question follows the pattern of a stack data structure(At the time when i am writing this answer). That is: ever time you add a new element, the new element replaces the previously added element as the first element.
I guess you want to get 1 as your first element, if you have added elements 1,2,3 in that order. Correct me if i am wrong.
In that case your linked list and it's retrieval should be like this:
(Note: i have avoided private vars , public getter , settter , etc; to make code easily readable. But readers should add them.)
class Node{ int x; Node next; }
class LinkedList
{ Node head,tail;
void add(int y)
{ Node node = new Node();
node.x=y;
if(head==null)
head = tail = node;
else
tail = tail.next = node;
}
int getFirst()
{ if(head!=null)
return head.x;
else
throw new java.util.NoSuchElementException("List is empty");
}
}
If you look at java.util.LinkedList, you will find methods that are conventionally used in linked lists. If this is not a homework question, then i suggest you do not reinvent the wheel. Just use the existing libraries.
If you have to use the stack data structure, and you cannot change it, then i suggest you have to change your getFirst() like this:
int getFirst()
{ if(tail!=null)
return tail.x;
else
throw new java.util.NoSuchElementException("List is empty");
}
If you not allowed to add Node tail in your code, then your getFirst() will look like this:
int getFirst()
{ if(head==null)
throw new java.util.NoSuchElementException("List is empty");
Node node = head;
while(node.next!=null)
node=node.next;
return node.x;
}
So I came across this code while studying linkedlists. The code here uses generics and I am having problem understanding some of the things here.
public static class Node<E>
{
E element;
Node <E> next;
public Node(E e,Node <E> n)
{
element=e;
next=n;System.out.println(next);
}
public E getelement() {return element;}
public Node<E> getnext(){ return next;}
public void setnext(Node <E> n)
{
next=n;
}
}
So what does class Node <E> mean?
I think E element; means element is of type E. Am I right?
Node <E> next; what does this mean?
The <E> by the class name declares that E as a generic type parameter - this means any instance of Node will be of some type, and this type will be decided by the code that instantiates it. new Node<String>() will create a node of type String, new Node<Integer>() creates a node of type Integer, and so on.
Where E is used in the class then reflects whatever type a particular instance has chosen, so if a have a node of type String, I know that element will be a String, and next will be a reference to another node containing a String.
The beauty of generics is that using this type parameter means I don't need to write a copy of this class for each type I want to use, while also being sure that all of the references will be of the type I expect - I won't get next returning an Integer when I'm expecting a String.
The link JB Nizet provides is a very good one - generics are quite a large and subtle topic, and if you wnat to learn about generics that tutorial will help you a lot.
I always learn best from example, so put Node to a simple use:
import java.awt.Point;
public class TestNode{
public static void main(String[] args) {
//assume you have 3 points
Point point1 = new Point(40,40);
Point point2 = new Point(80,120);
Point point3 = new Point(70,200);
//each point is connected to one other point. to represent such connection you
//can create a Node<Point> or in other words Node of Point.
//define the last node in the chain, which has no next node:
Node<Point> node3 = new Node<>(point3, null);
//Note: because Node<E> is generic you could define Node<Cats>, Node<Dogs>, Node<AnyType>
//define the point2-point3 connection
Node<Point> node2 = new Node<>(point2, node3);
//define point1-point2 connection
Node<Point> node1 = new Node<>(point1, node2);
//now put it to test. node1.getnext() return node2, node1.getnext().getelement() returns point2
System.out.println("Point 2 x-y " +node1.getnext().getelement().getX()
+"-"+node1.getnext().getelement().getY());
//now put it to test. node1.getnext().getnext() return node3
System.out.println("Point 3 x-y " +node1.getnext().getnext().getelement().getX()
+"-"+node1.getnext().getnext().getelement().getY());
}
}
You can easily find official docs and many other resources for such a big topic in Java, I'll try to explain it by "the process of re-creating generics".
Say you're going to implement the class Node given in the question, it's a basic building unit for LinkedList, so you define it as:
class Node {
private Node next;
public Node getNext() {
return next;
}
public void setNext(Node n) {
next = n;
}
}
but you need to store some data in each Node, don't you, otherwise this class is useless. Obviously one more field is necessary and the type you want to store is MyData, then it'll be:
class Node {
private MyData element;
private Node next;
public Node getNext() {
return next;
}
public MyData getElement() {
return element;
}
public void setElement(MyData element) {
this.element = element;
}
public void setNext(Node n) {
next = n;
}
}
One day you want to make your implementation a common library so it can be used by anyone, but one serious problem comes up which is people will not happy with that they can only store data of type MyData in your Node, they want to store whatever type they want, so you made a little change - declare the type of element to Object so that it can handle any type:
class Node {
private Object element;
private Node next;
public Node getNext() {
return next;
}
public Object getElement() {
return element;
}
public void setElement(Object element) {
this.element = element;
}
public void setNext(Node n) {
next = n;
}
}
Everything's good now, but some time later you receive some feedbacks from some picky users:
User A: everywhere I call Node.getElement() in my code, I get an Object type stuff and I need to do a type cast, which is inconvenient, it would be better if what I get from getElement is the type I want
User B: I want to only store type A but there's no way to prevent me put a type B into Node, I can't find this bug till exception happens during runtime, it would be better that compiler can help me to find the bug
So you feel that it'll be great if you can leave the decision of what type of data is allowed to put in Node to users, rather than hardcoded in implementation, which means what you'll put at the underscore of the statement private ___ element; is uncertain, you need it be a variable and specified by the user at the moment they use it, so a variable to the class, that's good, but you need a place to declare the variable before you can use it, finally you decide to put the declaration of the variable right after the class name, inside <>(a new syntax), then the code will be:
class Node<E> {
private E element;
private Node next;
public E getElement() {
return element;
}
public void setElement(E element) {
this.element = element;
}
public Node getNext() {
return next;
}
public void setNext(Node n) {
next = n;
}
}
almost done but wait: you're using Node by yourself - the field next, you need to follow the rule you just made: pass type info of element to Node at the time when you use it, so finally you got the code following:
class Node<E> {
private E element;
private Node<E> next;
public E getElement() {
return element;
}
public void setElement(E element) {
this.element = element;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> n) {
next = n;
}
}
Em....Sorry I didn't expect this to be so long...But hope it could be a little helpful to you.