Java中的toString覆盖 [英] toString Override in Java

查看:122
本文介绍了Java中的toString覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题来自作业。我必须在创建循环链接列表的类中覆盖toString()方法,实际上我有一个工作得很好的toString()方法,它将所有测试都传递给所有东西。所以我的项目是自动进行的,它显然不赞成我的方法100%。所以我的问题是:有没有更好的方法来编写这个更有效的toString()方法?

This question is from an assignment. I have to override a toString() method in a class that creates a circularly linked list and I actually have a toString() method that works great, it passes all of my tests everything. So my project is autograded and it apparently doesn't approve of my method 100%. So my question is: is there a better way to write this toString() method that would be more efficient?

public String toString()
    {
        if (size == 0)
        {
            return "[]";
        }
        else
        {
            String output = "";
            Node<E> tempNode = actualElement;
            while (tempNode.next() != actualElement)
            {
                if (output.equals(""))
                {
                    output = "[" + output + tempNode.data().toString();
                    tempNode = tempNode.next();
                }
                else
                {
                    output = output + ", " + tempNode.data().toString();
                    tempNode = tempNode.next();
                }

            }
            output = output + ", " + tempNode.data().toString() + "]";
            return output;
        }

如果我需要详细说明类结构,那么这更有意义请告诉我。

If i need to elaborate more on the class structure so that this makes more sense let me know.

推荐答案

使用 StringBuilder

StringBuilder builder = new StringBuilder();
builder.append("some text");
builder.append("more text");
return builder.toString();

这篇关于Java中的toString覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆