I need to pass an object (for example object from Class DATA) which is within another object (for example object from Class NODE) to another object (from class NODE)?
The Node objects are nodes of a tree. The tree implementation is :
public class Tree {
private Node rootElement;
public Tree() {
super();
}
public Node getRootElement() {
return this.rootElement;
}
public void setRootElement(Node rootElement) {
this.rootElement = rootElement;
}
and then for Node I have:
public class Node {
public MyNode data;
public List<Node> children;
public int childNo;
public Node() {
super();
}
public Node(MyNode data) {
this();
setData(data);
}
public Node(MyNode data, int childNo) {
this();
setData(data);
this.childNo=childNo;
}
public void setChildren(List<Node> children) {
this.children = children;
}
public void addChild(Node child) {
if (children == null) {
children = new ArrayList<Node>();
}
children.add(child);
}
public MyNode getData() {
return this.data;
}
public void setData(MyNode data) {
this.data = data;
}
and for Mynode I have :
public class MyNode {
public String ID = new String(); //UUID
protected String parentID;
MyNodesDATA d = new MyNodesDATA();
public MyNode() {
setID(UUID.randomUUID().toString());
}
public MyNodesDATA getMyNodesDATA () {
return this.MyNodesDATA ;
}
public void setData(MyNodesDATA d) {
this.MyNodesDATA = data;
}
and this is MyNodesDATA
public class MyNodesDATA {
int iD;
String name;
}
So each node of the tree has an object of MyNode Type and each MyNode Object has a data as an object from MyNodesDATA class. I have already initialised the tree with a predefined structures of hierarchical nodes using some recursive methods which I didn't put here ...
Now, nodes of the tree in lover levels process their data and need to send them to their parents (USING THEIR PARENT ID). I stuck here... how a node (an object) can send it's data to another node (another object) (let say its parent in this scenario) using only one ID variable of the other object ... in a simpler way I need a method to get (ID and DATA) and send the data to the object which has the ID !! and of course there should be another function or event handler in receiver side to take action once receives a Data ....
In your example, Node does not have an object of DATA within it; you've simply initialised one in the constructor then allowed it to go out of scope. You also need to modify your constructor if you want to pass in a DATA object, so change Node to be:
public class Node {
int iD;
DATA d;
public Node(){
d = new DATA();
}
public Node(DATA d){
this.d = d;
}
}
so that you have the DATA instance stored. Then simply provide a getter, e.g.:
public DATA getData() {
return d;
}
and then you can do:
public class MAIN {
public static void main(String[] args) {
Node node1 = new Node();
Node node2 = new Node(node1.getData());
}
}
First of all, you probably want to make the DATA instance created in the Node constructor an instance member. Otherwise it can be released by the garbage collector once the constructor is done.
Then can either pass the DATA parameter to a constructor of Node, or you can have a setter method that would accept a DATA parameter.
public class Node {
int iD;
private DATA d;
public Node(){
this.d = new DATA(); // or this(new DATA());
}
public Node(DATA d){
this.d = d;
}
public void setData (DATA d) {
this.d = d;
}
public DATA getData() {
return this.d;
}
}
Now you have several options for 2 Node instances to share the DATA member :
public class MAIN {
public static void main(String[] args) {
DATA data = new DATA();
Node node1 = new Node(data);
Node node2 = new Node(data);
}
}
or
public class MAIN {
public static void main(String[] args) {
Node node1 = new Node();
Node node2 = new Node(node1.getData());
}
}
or
public class MAIN {
public static void main(String[] args) {
Node node1 = new Node();
Node node2 = new Node(null);
node2.setData (node1.getData());
}
}
Related
I have a database table with parent child relationship and any parent can have any number of children but there will only be 1 parent at the root level. Data looks like below:
TagID ParentTagID TagName
-------------------------------
1 null a
2 1 b
3 1 c
4 1 d
5 2 e
6 4 f
7 2 g
I want to fetch the records in java in a tree format. Although I can achieve this at SQL level itself using the below SQL but I want to extract the data from database as it is and perform the processing at java level so that the connection between java and SQL could be of minimum duration to avoid any latency from database side.
with cte as
(
select * from TagValue
where ParentTagID is null
union all
select s.* from TagValue s
join cte c on s.ParentTagID = c.TagID
)
select * from cte
Using Java with taking help from other useful links, I have created a tree as per below:
public class MyTreeNode<T> {
private T data = null;
private List<MyTreeNode<T>> children = new ArrayList<MyTreeNode<T>>();
private MyTreeNode<T> parent = null;
public MyTreeNode(T data) {
this.data = data;
}
public void addChild(MyTreeNode<T> child) {
child.setParent(this);
this.children.add(child);
}
public void addChild(T data) {
MyTreeNode<T> newChild = new MyTreeNode<T>(data);
newChild.setParent(this);
children.add(newChild);
}
public void addChildren(List<MyTreeNode<T>> children) {
for (MyTreeNode<T> t : children) {
t.setParent(this);
}
this.children.addAll(children);
}
public List<MyTreeNode<T>> getChildren() {
return children;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
private void setParent(MyTreeNode<T> parent) {
this.parent = parent;
}
public MyTreeNode<T> getParent() {
return parent;
}
}
While inserting objects in this tree, I can use the below code:
MyTreeNode<Integer> root = new MyTreeNode<Integer>(1);
MyTreeNode<Integer> child1 = new MyTreeNode<Integer>(2);
child1.addChild(3);
child1.addChild(4);
MyTreeNode<Integer> child2 = new MyTreeNode<Integer>(5);
child2.addChild(6);
root.addChild(child1);
root.addChild(child2);
root.addChild(7);
root.addChildren(Arrays.asList(new MyTreeNode<Integer>(8),
new MyTreeNode<Integer>(9), new MyTreeNode<Integer>(10)));
But this is a static code whereas the number of tags could be dynamic. I need a recursive solution to find a node based on ParentTag value and then insert the new tag as its child. Is there a recursive solution to do this? If there is any other out of the box data structure in Java 1.8 to perform this operation, that would also be useful.
Given a ResultSet, you would like to build your tree structure naturally, as follows:
while (... has more rows ...) {
addNode(rs.ParentTagID, rs.TagID);
You need some type of container to store your tree nodes in. You could use a List however the performance will suffer when building the tree; adding a child requires finding its parent, and a list offers no quick way to do this. A Map
however provides O(1) lookup.
The helper method addNode will keep the tree in tact: Find the parent, and add the child accordingly.
In summary the dynamic approach you are looking for is to iterate the result set, and repeatedly call addNode() passing both the parentId and childId (which is stored in the database). The root node is a special case (where parentId = null or 0) and is handled by addNode().
There was a slight modification to MyTreeNode to return the object (when adding a child); it used to be of type void.
Here is some sample code showing this approach.
public class MutipleTreeNode {
static Map<Integer, MyTreeNode<Integer>> nodeMap = new HashMap<>();
public static void main(String[] args) {
// Here you would process your result set
// Rather than simulate a result set, I just build some nodes manually
addNode(0, 1); // Root
addNode(1, 2);
addNode(1, 3);
addNode(1, 4);
addNode(2, 5);
addNode(2, 7);
addNode(4, 6);
printTree();
}
private static void printTree() {
for (MyTreeNode<Integer> node : nodeMap.values()) {
if (node.getParent() == null)
System.out.print("Root node: ");
System.out.println(node.getData()+"; children="+node.getChildren());
}
}
private static void addNode(int parentId, int childId) {
MyTreeNode<Integer> childNode, parentNode;
if (nodeMap.isEmpty())
childNode = new MyTreeNode<Integer>(childId);
else {
parentNode = nodeMap.get(parentId);
childNode = parentNode.addChild(childId);
}
nodeMap.put(childId, childNode);
}
public static class MyTreeNode<T> {
private T data = null;
private List<MyTreeNode<T>> children = new ArrayList<MyTreeNode<T>>();
private MyTreeNode<T> parent = null;
public MyTreeNode(T data) {
this.data = data;
}
public void addChild(MyTreeNode<T> child) {
child.setParent(this);
this.children.add(child);
}
public MyTreeNode<T> addChild(T data) {
MyTreeNode<T> newChild = new MyTreeNode<T>(data);
newChild.setParent(this);
children.add(newChild);
return newChild;
}
public void addChildren(List<MyTreeNode<T>> children) {
for (MyTreeNode<T> t : children) {
t.setParent(this);
}
this.children.addAll(children);
}
public List<MyTreeNode<T>> getChildren() {
return children;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
private void setParent(MyTreeNode<T> parent) {
this.parent = parent;
}
public MyTreeNode<T> getParent() {
return parent;
}
#Override
public String toString() {
return "[data=" + data + "]";
}
}
}
Creates the output:
Root node: 1; children=[[data=2], [data=3], [data=4]]
2; children=[[data=5], [data=7]]
3; children=[]
4; children=[[data=6]]
5; children=[]
6; children=[]
7; children=[]
im trying to create a linked list but i keep getting that error, i am new to linked list and cant figure out whats happening. the code seems to work other lists that insert two data types into the node class.
EDIT: i am using netbeans and all 3 classes are in the same package, and they are the only
main class
public class assignment6 {
public static void main(String[] args) {
PQueue p = new PQueue();
p.push(22);
p.push(11);
p.push(2);
p.display();
/*
*/
}
}
linked list class
class PQueue {
public Node firstL;
PQueue(){
firstL = null;
}
public boolean isEmpty(){
return (firstL == null);
}
public void push(int num){
Node n = new Node(num);
n.next = firstL;
firstL = n;
}
public void display(){
Node link = firstL;
while(link != null){
link.display();
link=link.next;
}
}
}
node class
public class Node {
public int num;
public Node next;
public Node(int num){
this.num = num;
}
public void display(){
System.out.println(num);
}
}
I've come up with the following as an attempt to create a general tree in java:
import java.util.*;
public class GeneralNode<T>{
private T data = null;
private Vector<GeneralNode<T>> children =
new Vector<GeneralNode<T>>();
public GeneralNode(){
this(null);
}
public GeneralNode(T d){
data = d;
}
public Vector<GeneralNode<T>> getChildren(){
return children;
}
public void addChild(T d){
GeneralNode<T> c = new GeneralNode<T>(d);
this.children.add(c);
}
public void addChild(GeneralNode<T> c){
this.children.add(c);
}
public T getData(){
return data;
}
public void setData(T newData){
data = newData;
}
public boolean isLeaf(){
return(children.isEmpty());
}
public Vector getChildrenData(){
Vector<T> result = new Vector<T>();
for(int i = 0; i < children.size(); i++)
result.add(children.elementAt(i).getData());
return result;
}
}
This works great for storing information. It allows me to create a node and insert more nodes in that node, along with having one type of information in each node. Unfortunately, it seems like I can't reference a "parent" node with this class. Essentially, I'm nesting vectors within vectors, so I can't actually reference the node holding the node.
I'm sure I have to make a separate GeneralTree class in order to get this done, but I'm not sure how I'd go about doing so. I had the idea of assigning the root as a GeneralNode, and having a "previous" and "next" node as being the parent and children respectively. This is what I've come up with so far:
import java.util.*;
public class GeneralTree<T>{
private GeneralNode<T> root;
private GeneralNode<T> parent;
private GeneralNode<T> children;
public GeneralTree(){
this(null);
}
public GeneralTree(T d){
this(d, null);
}
/* I don't know what to do here. I want
* to assign a parent node to every
* tree I make, but if I keep the
* second parameter as GeneralNode<T>, wouldn't
* that mean I could only ever have one GeneralTree?
*/
public GeneralTree(T d, GeneralNode<T> p){
root = new GeneralNode<T>(d);
parent = p;
}
}
I've written comments on the constructor I'm confused on. I hope I've explained my problem well enough. If anyone can help me with this that'd be great.
As #JohnBollinger said, you can keep a reference of parent node inside each nodes. If you do that you must set parent nodes inside addChild methods.
import java.util.Vector;
public class GeneralNode<T>{
private T data = null;
private Vector<GeneralNode<T>> children =
new Vector<GeneralNode<T>>();
private GeneralNode<T> parentNode;
//constructors
private void setParent(GeneralNode<T> parentNode) {
this.parentNode = parentNode;
}
public void addChild(T d){
GeneralNode<T> c = new GeneralNode<T>(d);
c.setParent(this);
this.children.add(c);
}
public void addChild(GeneralNode<T> c){
c.setParent(this);
this.children.add(c);
}
//other methods
}
I have created this Node class for a singly linked list:
class Node{
int item;
Node next;
Node(int v){
item = v;
next = null;
}
}

I want to make a search for the node with the highest key in a method called findmax.But i want to check if the list is empty, and if so , to return null, otherwise return the node with the highest key. This is what i have done:
Node findmax(Node h){
if(h==null)
return null;
else{
//search
}
All i want to know is if the check i make to see if the list is Empty is correct.
Yes, the check you've done is correct if:
Node n = null;// init empty list
and:
n = new Node(3);// first item
However, I suggest you to create a list struct which is independent from the item it concatenates. That's what I mean:
The Node class:
public class Node
{
int value;
public Node(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
The list struct:
public interface IList
{
public int getNodeNumbers();
}
public class EmptyList implements IList
{
#Override public int getNodeNumbers() {
return 0;
}
}
public class ConsList implements IList
{
private Node node;
private IList next;
public ConsList(Node node, IList next) {
this.node = node;
this.next = next;
}
#Override public int getNodeNumbers() {
return 1 + next.getNodeNumbers();
}
}
How to use it:
public class Main
{
public static void main(String[] args) {
IList list1 = new ConsList(new Node(1),
new ConsList(new Node(2),
new ConsList(new Node(3),
new ConsList(new Node(4),
new EmptyList()))));
IList list2 = new EmptyList();
System.out.println(list1.getNodeNumbers() + " - " + list2.getNodeNumbers());
}
}
And now, a list is empty (you can create your own method isEmpty() into the IList interface) when getNodeNumbers() returns 0.
Hi all im wondering how to display all nodes in a linked list. Heres the code I have so far. The Manager class is supposed to operate the list. The movieNode class creates new list nodes for the movie. I know I have to use other things as well but im just trying to get the first element of the list to display for starters.
public class Manager {
MovieNode head;
public Manager (){
head=null;
}
public void Add (MovieNode data) {
if (head==null){
head=data;
}
}
public void Display () {
int i=1;
MovieNode temp=head;
System.out.println("Displaying Movies");
while (head!=null) {
System.out.println(temp.getData().getName());
head=null;
}
}
}
also, the code for the MovieNode class
public class MovieNode {
private Movie data;
private MovieNode next;
public MovieNode (){
data=null;
next=null;
}
public MovieNode (Movie data){
setData(data);
}
public void setData (Movie data){
this.data=data;
}
public Movie getData (){
return data;
}
}
Hopefully this will help you get started. Here are some pointers:
Manager Class
You don’t need an explicit constructor for Manager, as you can initialize the head variable in line and you’re not passing any other information to the constructor
Method names in Java are conventionally camel case and start with lower-case letter
When you add a new item to the linked list, you can pass in just the data and create the node in the add method
Assuming you don’t need to maintain any special order, you can insert the new item to the head of the list. This saves the time to go through the whole list to find the tail or keeping a reference to the tail.
To display all the movies, you just need to start with the head and check if there is a node next in list. If you don’t need to implement this custom method, I would recommend implementing the class as Iterable. A SO discussion on this topic can be found here
MovieNode Class
You only need one constructor that takes the data and sets the private variable
You also need the getter and setter for the next variable in order to hold the list structure and iterate through the list
The toString() implementation will allow to print an instance of this class directly, as in displayAllMovies() method
Movie Class
This class just holds the title of the movie for now, but you can extend it according to your spec.
Here is the code:
public class Manager {
MovieNode head = null;
public void addMovie(Movie data) {
MovieNode newNode = new MovieNode(data);
if (head == null) {
head = newNode;
} else {
newNode.setNext(head);
head = newNode;
}
}
public void addMovieInOrder(Movie data) {
MovieNode newNode = new MovieNode(data);
if (head == null) {
head = newNode;
} else {
MovieNode higher = head;
MovieNode lower = null;
// find the right position for newNode
while(higher != null){
if(newNode.compareTo(higher) > 0){
lower = higher;
higher = higher.getNext();
}
else break;
}
newNode.setNext(higher);
if(higher == head) head = newNode; //inserting as head
else lower.setNext(newNode);
}
}
public void displayAllMovies() {
MovieNode node = head;
if (node == null) {
System.out.println("The list is empty!");
}
do {
System.out.println(node.getData());
node = node.getNext();
} while (node != null);
}
public static void main(String[] args) {
Manager manager = new Manager();
manager.addMovieInOrder(new Movie("ddd"));
manager.addMovieInOrder(new Movie("ccc"));
manager.addMovieInOrder(new Movie("aaa"));
manager.addMovieInOrder(new Movie("bbb"));
manager.displayAllMovies();
}
}
Movie Node class:
public class MovieNode implements Comparable<MovieNode> {
private Movie data;
private MovieNode next = null;
public MovieNode(Movie data) {
this.data = data;
}
public void setData(Movie data) {
this.data = data;
}
public Movie getData() {
return data;
}
public void setNext(MovieNode node) {
this.next = node;
}
public MovieNode getNext() {
return next;
}
#Override
public String toString() {
return data.toString();
}
#Override
public int compareTo(MovieNode otherMovieNode) {
return data.compareTo(otherMovieNode.getData());
}
}
Movie class:
public class Movie implements Comparable<Movie> {
private String title;
public Movie(String title) {
this.title = title;
}
#Override
public String toString() {
return title;
}
#Override
public int compareTo(Movie otherMovie) {
return title.compareTo(otherMovie.title);
}
}