HelpNeeder
HelpNeeder

Reputation: 6480

Replacing multiple variables for one object?

My job was to:

Revise the Node class to a generic one so that it can handle folders and files in a file system shown below.

And also:

First, you need to modify the Node class so that both 'size' and 'name' will be replaced by one object.

Now, I did the first part where we change the class to use generic types. I'm stuck at second problem. I don't know how to pass single object instead of 2 variables and then do bunch of computation within it.

How would I substitute multiple variables for single object here? I've been trying to change types and move things around but my code keeps failing as soon as I remove those 2 variables.

Code:

class Node<T>
   {
   public String name;
   public int size;
   public Node<T> leftChild;
   public Node<T> rightChild;

   public void displayNode()
      {
      System.out.print('{');
      System.out.print(name);
      System.out.print(", ");
      System.out.print(size);
      System.out.print("} ");
      }
   }  // end class Node

Upvotes: 1

Views: 123

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213203

You would need to create a Custom Data Class. That class will wrap your required variables as attribute.

For e.g., in your case: -

public class MyData {
    private String name;  // Your data are enclosed in the data object MyData
    private int size;

    /** Constructors **/
    /** Getters and Setters **/
}

Now, wherever, you are using those variables, use an instance of this class. And your generic class would be changed as per @TedHopp's answer.

And your Node class will be instantiated like this: -

Node<MyData> node = new Node<MyData>();

So, your T now becomes MyData. So, if you want to access size and name, you would have to do it like this: -

node.getMyData().getSize();
node.getMyData().getName();

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234795

I would redesign it like this:

class Node<T> {
    public T data;
    public Node<T> leftChild;
    public Node<T> rightChild;

    public void displayNode() {
        System.out.print('{');
        System.out.print(data.toString());
        System.out.print("} ");
   }
   . . .
}

EDIT One way to rewrite your find method is for it to find a particular T value:

public Node<T> find(Comparable<T> target) {
    Node<T> current = root;
    int comp = target.compareTo(current.data);
    while (comp != 0) {
        if (comp < 0)
            current = current.leftChild;
        else
            current = current.rightChild;
        if(current == null)
            return null;
    }
    return current;
}

Upvotes: 2

Related Questions