public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insertFront(1);
list.insertFront(2);
list.insertFront(3);
System.out.println(list.toString());
}
String toString() {
String result = "";
LinkedListNode current = head;
while(current.getNext() != null){
result += current.getData();
if(current.getNext() != null){
result += ", ";
}
current = current.getNext();
}
return "List: " + result;
}
Answer from Marin on Stack Overflowpublic static void main(String[] args) {
LinkedList list = new LinkedList();
list.insertFront(1);
list.insertFront(2);
list.insertFront(3);
System.out.println(list.toString());
}
String toString() {
String result = "";
LinkedListNode current = head;
while(current.getNext() != null){
result += current.getData();
if(current.getNext() != null){
result += ", ";
}
current = current.getNext();
}
return "List: " + result;
}
As has been pointed out in some other answers and comments, what you are missing here is a call to the JVM System class to print out the string generated by your toString() method.
LinkedList myLinkedList = new LinkedList();
System.out.println(myLinkedList.toString());
This will get the job done, but I wouldn't recommend doing it that way. If we take a look at the javadocs for the Object class, we find this description for toString():
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
The emphasis added there is my own. You are creating a string that contains the entire state of the linked list, which somebody using your class is probably not expecting. I would recommend the following changes:
- Add a toString() method to your LinkedListNode class.
- Update the toString() method in your LinkedList class to be more concise.
- Add a new method called printList() to your LinkedList class that does what you are currently expecting toString() to do.
In LinkedListNode:
public String toString(){
return "LinkedListNode with data: " + getData();
}
In LinkedList:
public int size(){
int currentSize = 0;
LinkedListNode current = head;
while(current != null){
currentSize = currentSize + 1;
current = current.getNext();
}
return currentSize;
}
public String toString(){
return "LinkedList with " + size() + "elements.";
}
public void printList(){
System.out.println("Contents of " + toString());
LinkedListNode current = head;
while(current != null){
System.out.println(current.toString());
current = current.getNext();
}
}
How do I print a Linked List using a ToString method?
Printing contents of nodes in linked lists
Printing elements of a linked list in java - Stack Overflow
java - Printing out a Linked list - Stack Overflow
Hello,
I'm trying to learn LinkedLists but I can't figure out how to print it using the ToString method.
import java.util.LinkedList;
public class MyString {
private LinkedList<Character> list;
public MyString(){ //constructor
this.list = list;
}
public void append(char c){ //add char to list
list.add(c);
}
public int indexOf(char c){ //return the index of a char
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == c) {
return i;
}
}
return -1;
}
public char charAt(int index) throws IndexOutOfBoundsException{ //return the char at an index
return list.get(index);
}
public String toString(){ //print list
return list;
}
public static void main(String[] args) {
}
}I googled around but didn't quite understand the concept.
Currently the error I'm getting for my ToString method is: Type mismatch: cannot convert from LinkedList<Character> to String
Any help is appreciated :)
Hey y'all. Learning about Linked Lists in my class at the moment, and my professor wasn't able to teach us much about linked lists (family issues). He's unavailable until the end of the semester, but with that being two weeks away, I'm in a bind.
Tasked with an assignment that creates a linked list of movies. The 'movie' class creates objects with 5 attributes along with an override of the toString method. In the actual linked lists class, there is a show_all() method that's called in the main method - it utilizes the toString method in order to print a label for the movie objects. However, my show_all() method isn't displaying the label when called on. Here's the method:
public static class BlueRayDisk{
public String title, director;
public int yearOfRelease;
public double cost;
public BlueRayDisk(String t, String d, int y, double c){
this.title = t;
this.director = d;
this.yearOfRelease = y;
this.cost = c;
}
public String toString(){
return "$" + cost + " " + yearOfRelease + " " + title + ", " + director;
}
}
public static class Node{
public BlueRayDisk disk;
public Node next;
}
public static class BlueRayCollection{
private Node head = null;
public void add(String title, String director, Integer year, Double cost){
Node tempNode = new Node();
tempNode.disk = new BlueRayDisk(title,director,year,cost);
if (head == null)
{
head = tempNode;
}
else{
Node current = head;
while(current.next!= null){
current = current.next;
}
current.next = tempNode;
}
}
public void show_all(){
Node current = head;
while(current.next != null){
System.out.println(current.disk);
current = current.next;
}
}
}
public static void main (String[] args){
BlueRayCollection a = new BlueRayCollection();
int user;
String titl,dir;
Integer year;
Double cost;
Scanner scan = new Scanner(System.in);
do{
System.out.println("0. Quit\n" +
"1. Add BlueRay to collection\n" +
"2. See collection");
user = scan.nextInt();
switch(user){
case(0):
break;
case(1):
System.out.println("What is the title?");
titl = scan.next();
System.out.println("What is the director?");
dir = scan.nextLine();
scan.nextLine();
System.out.println("What is the year of release?");
year = scan.nextInt();
System.out.println("What is the cost?");
cost = scan.nextDouble();
a.add(titl,dir,year,cost);
break;
case(2):
a.show_all();
break;
}
}while (user != 0);
}
Am I missing something? I am struggling with the concept of linked lists a little, but I was able to get my add method to work.
EDIT: Added the LinkedList class (named BlueRayCollection) for clarification along with the node class. Main method shows the add/print all methods in action.
In your append statement, you add the first element twice:
public void append(int data){
if(head==null){
head=new Node(data); // <--- Added here
}
Node current;
current=head;
while(current.next!=null){
current=current.next;
}
current.next=new Node(data); // <--- And then again here
}
So your linked list actually contains the first element twice. It doesn't happen afterwards, because there is already a head to the list.
You should add a return after the head = new Node(data), or have an else statement:
public void append(int data){
if(head==null){
head=new Node(data);
} else {
Node current;
current=head;
while(current.next!=null){
current=current.next;
}
current.next=new Node(data);
}
}
You've got two bugs.
(1) You're adding the first element twice. You've got
if(head==null){
head=new Node(data);
}
but then you continue on and add it again.
(2) When you print out the list, you're stopping when current.next == null - so you're stopping before you get to the last element. The condition on your while loop needs to be
while(current != null) {
instead of checking current.next.
If your list implements the java.util.list interface you can use, this line to convert the list to an array and print out the array.
System.out.println(Arrays.toString(list.toArray()));
Well, by default every class in java got toString method from Object class.
The toString method from Object class will print class name followed with @ and hash code.
You can override toString method for the LinkedList.
For example:
class MyLinkedList extends LinkedList
{
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "MyLinkedList [size=" + size + ", first=" + first + ", last="
+ last + ", modCount=" + modCount + "]";
}
}
Then you can print it:
MyLinkedList list = new MyLinkedList ();
System.out.println(list);
Add a method toString to your LinkedList class
public String toString() {
Node<T> curr = head;
StringBuilder sb = new StringBuilder();
sb.append("LinkedList [");
while (curr != null) {
sb.append(curr.data);
if (curr.nextNode != null) {
sb.append(", ");
}
curr = curr.nextNode;
}
sb.append("]");
return sb.toString();
}
Then call it in your main method :
System.out.println(list.toString());
You have to override the toString() method in your LinkedList<T> class