How do I loop through an array in Java? - java

Related to my question about how to build a tree-like structure, the data I receive from the server are in arrays like this: {School Chair Table Chalk}
How can I loop through this so that:
School becomes parent of Chair
Chair becomes parent of Table
Table becomes parent of Chalk

Assuming a Node class that offers a constructor which accepts the node's value as an argument and method addChild that adds another Node as a child and sets itself as the child's parent, the code could look like this:
Node currentNode = null;
for(String value: array) {
Node node = new Node(value);
if(currentNode != null) {
currentNode.addChild(node);
}
currentNode = node;
}

Are they always in a list that becomes hierarchical in order? I would suggest creating a simple wrapper class...pardon my syntax, as I've been playing in C# for a while now:
public class Node {
public string description;
public Node child;
public Node(List<string> descriptions) {
this.description = descriptions.RemoveAt(0);
if (descriptions.Count > 0) {
this.child = new Node(descriptions); //create child node with remaining items
}
}
}
This will take issue if you pass in a list w/ zero items to the constructor, but that's easily remedied.

Related

Understanding setup for doubly linked list in Java

I am working on a doubly linked list in Java. So that I can create functions, I'm first working to understand the setup.
I have this code. I have started comments with what each line does. Looking at tutorials and I want to make sure I understand this correctly. I still get a little confused on using classes.
If I create a new node by Node x = new Node(); - I am creating a new node of class Node. So that creates an instance using "static class Node {"
Each Node created contains a int item, Node next, and Node prev, that I will set in my functions. The int item I assume is the contents of the Node.
What does the line "public Node() {}" do?
public class MyDeque {
Node first = null; //instance variable, first is of type node and is set to null
Node last = null; //instance variable, last is of type node and is set to null
int N = 0; //keeping track of number of nodes
static class Node {
public Node() { }
public int item;
public Node next; //next is of type node
public Node prev; //prev is of type node
}
To understand this setup for Double-Linked-List you need to understand how a constructor works; A constructor is like a method, which is used to initialize properties of a class when the object of this class is initialized in memory for the first time.
Let's take your code for an example, I modified it in a proper way to understand why and how constructors used in Java -
public class MyDeque {
Node first;
Node last;
int N;
public MyDeque(){
this.first = null;
this.last = null;
this.N = 0;
}
static class Node {
int item;
Node next;
Node prev;
public Node() {
this.next = null;
this.prev = null;
}
public void setItem(int item) {
this.item = item;
}
public int getItem(){
return this.item;
}
// ... public getters for other items
}
As you can see two constructors public Node(){} and public MyDeque(){} are used to set values for the properties of those objects when they are initialized in memory for the first time.
Later, of course, you can set / unchange / change values of properties using the setter method or using the "." operator but remember constructor will always take place when the objects are initialized or reinitialized in memory for the first time.

How to find the first value in a linked list?

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;
}

Depth first search in java - how to go back to parent node?

I'm trying to do a depth first search in Java recursively. At the moment, the code runs through my graph fine, but it never backtracks to find a route when they're are no more nodes to visit. I'm having a bit of a mental block honestly. What would be the best way to go back to the parent node?
Here is my code so far:
private final Map<Character, Node> mNodes;
private final List<Edge> mEdges;
public DepthFirstSearch(Graph graph){
mNodes = graph.getNodes();
mEdges = new ArrayList<>(graph.getEdges());
for(Node node : mNodes.values()){
node.setVisited(false);
}
}
public void depthFirstSearch(Node source){
source.setVisited(true);
List<Node> neighbours = source.getNeighbours(mEdges);
for(Node node : neighbours){
if(!node.isVisited()){
System.out.println(node.getName());
depthFirstSearch(node);
}
}
}
And the getNeighbour code:
public List<Node> getNeighbours(List<Edge> edges) {
List<Node> neighbours = new ArrayList<>();
for(Edge edge : edges){
if(edge.getFrom().equals(this)){
neighbours.add(edge.getTo());
}
}
return neighbours;
}
Added code for trying Jager's idea:
public void depthFirstSearch(Node source){
source.setVisited(true);
List<Edge> neighbours = source.getNeighbouringEdges(mEdges);
for(Edge edge : neighbours){
if(!edge.getTo().isVisited()){
System.out.println(edge.getTo().getName());
depthFirstSearch(edge.getTo());
}else{
depthFirstSearch(edge.getFrom());
}
}
}
Well, typically you have a root node that has children. Each child can have children of its own. So you would rather do:
public void depthFirstSearch(Node source)
{
for(Node node : source.getChildren())
{
System.out.println(node.getName());
depthFirstSearch(node);
// and right here you get your back tracking implicitly:
System.out.println("back at " + node.getName());
}
}
Note that I do not have a necessity for a member visited...
Edit:
Now that you provided your data structure, let me propose another approach:
class Node
{
// all that you have so far...
private char mId;
private List<Node> mChildren = new ArrayList<Node>();
public char getId()
{
return mId;
}
public List<Node> getChildren()
{
return Collections.unmodifiableList(children);
}
// appropriate methods to add new children
}
The id replaces the key of your map. Then you simply have a root Node mRoot to start with somewhere. This is the typical way to implement trees.
You might want to go up from a child node directly. Then you'd additionally need a private Node parent; in the node class (immediately being set to this when adding a child to the private list and set to null, when being removed). You won't use this for backtracking, though, so the depth first search above remains unchanged.
Guessing: you are "getting" the neighbors for mEdges which seems to be a field of the surrounding class.
Most likely, you should ask each node for its own edges upon visiting it.

change values of array of a class in java

I am writting a program that performs an a star search throughout a map. I have created a class that hold all the nodes of the map.
public Node {
Node up_node, right_node, down_node, left_node;
}
public class Star {
public static void main(String args[]) {
Node a=new Node();
Node b=new Node();
Node h=new Node();
Node here=new Node();
Node[] NextNode;
NextNode = new Node[10];
for(int i=0;i<10;i++) {
NextNode[i]=new Node();
}
int j=0;
a.up_node=h;
a.right_node=b;
b.left_node=a;
h.down_node=a;
//if certain conditions are met
NextNode[j].here_node=a.up_node;
//what i was hoping to do is copy the node a.up which is h
}
}
into NextNode[0] in this case. However it keeps returning a memory address of some sort : test.Node#10b28f30: test being the name of the package, please help!
#override the toString() method to display the internal property of your class.
By default, java display the full class name#hashCode value.
Variables in Java are object references not actual objects. NextNode[j].here_node = a.up_node; will make NextNode[j].here_node and a.up_node point to the same object. Is this not what you want?
If you wanted to make a completely new copy of the object, then you can implement that in the Node class:
public class Node {
Node up_node, right_node, down_node, left_node;
public Node clone() {
Node ret = new Node();
// copy the properties
ret.up_node = this.up_node;
...
return ret;
}
}
Now
NextNode[j].here_node = a.up_node.clone();
will make a copy (although it's only a shallow one -- the copy will point to the same objects via its fields as opposed to copies of them).
I assume your confusion about the code returning "an address" comes because you tried to print a node, e.g.
System.out.println(a.up_node);
You'll get something like test.Node#10b28f30, but try
System.out.println(NextNode[j].here_node);
and you should get exactly the same string, indicating that they're pointing to the same object.
To get something nicer, you must override Node's implementation of toString(). Here's an example that will give each Node a unique number:
public class Node {
Node up_node, right_node, down_node, left_node;
// how many nodes were created
private static int count = 0;
// the number of this node
private int number;
public Node() {
// increment the number of nodes created
++Node.count;
// assign that number to this node
this.number = Node.count;
}
public String toString() {
return "Node #" + this.number;
}
}
We know that every class that we write are child of Object class. When we print a child of an Object it prints its toString() method. By default it is a hashed value of memory location. So it prints sort weird things. if we #overriding toString method to return something more meaningful to us then we can solve this problem. If we can name our node class someway I think we can keep track of them easily
class Node(){
String nameOfNode;
//contractor to keep track of where it goes.
public Node(String a){
nameOfNode=a;
}
//when we will print a Node it is going to print its name
public String toString(){
return nameOfNode;
}
}
Then it will print the name of the node. And it will stop showing that weird memory address.
and replace your new Node() with distinct name new Node("a name")

Order of recursive tree index?

I have tree where all leafs have index, when tree is rescursively lodaded form database, database will order tree by indexes. First it gets root nodes sorted by index and so on. Now I need to implement action how user can sort these indexes by pressing up/down arrow icons. When user presses down then index should take index that is under it's own index and when up arrow is pressed it should do vice versa. I just don't know what would be best way to implement this kind of functionality.
Since your question is a bit vague, this answer assumes you know what you are doing when it comes to the database stuff (I would reccommend hibernate for java if not) and the following code is meant to give you some ideas for implementing your solution.
//If I have understood your question, you want two nodes to swap position in the tree structure
public static swapNode(Node parent, Node child)
{
Long superId = parent.getParentId();
child.parentId(superId);
parent.setParentId(child.getId());
child.setId(parentId);
//update children lists of parent and child
//update parent ids of children lists
//save changes to database
}
//create tree structure from database. Assumes nodes have been loaded from a database
//table where each row represents a node with a parent id column the root node which has parent id null)
//invoke this with all nodes and null for parentId argument
public static List<Node> createNodeTree(List<Node> allNodes, Long parentId)
{
List<Node> treeList = new ArrayList<Node>();
for(Node node : nodes)
{
if(parentIdMatches(node, parentId))
{
node.setChildren(createNodeTree(allNodes, node.getId()));
treeList.add(node);
}
}
return treeList;
}
private static boolean parentIdMatches(Node node, Long parentId)
{
return (parentId != null && parentId.equals(node.getParentId()))
|| (parentId == null && node.getParentId() == null);
}
//The objects loaded from the database should implement this interface
public interface Node
{
void setParentId(Long id);
Long getParentId();
Long getId();
List<Node> getChildren();
void setChildren(List<Node> nodes);
}

Categories

Resources