Home > OS >  Print object from singly linked list
Print object from singly linked list

Time:09-23

I have an object that stores a few ints and a string. I assign this object to a SLL here:

BirthdayCalc object = new BirthdayCalc(month, day, year, result, birthdayStr);
                    
                    
list.addLast(object);

How would I print out specific parts of this object in the SLL? I want to read the element from the node, and then take month day and year, and birthday string. Since this object is created in a loop I need to be able to print the element of each new node.

CodePudding user response:

One possible solution would be to have a display method in your SinglyLinkedList class, like this:

public void display() {    
    //Node current will point to head    
    Node current = head;    
          
    while(current != null) {    
        //Prints each node by incrementing pointer    
        System.out.print("Month: "   current.birthdayCalc.getMonth()   " ");    
        current = current.next;    
    }    
}   

Alternatively, you could implement Iterable and Iterator interfaces as explained here.

CodePudding user response:

Your Linkedlist can be given the type safety of the BirthdayCalc class objects

List<BirthdayCalc> ll = new LinkedList<>();

Now since you need to only print the specific properties you can you use a for-each loop:

for( BirthdayCalc bc : ll ) {
    System.out.println(bc.month  " "  bc.year " " bc. birthdayStr);
}

You can alternatively use iterator as well. Moreover, access the properties using Getter and Setter methods.

  •  Tags:  
  • java
  • Related