链接列表中的字符串,对象的高效构造函数

时间:2015-03-03 01:28:56

标签: java constructor linked-list

我正在努力在名为LString的对象中构建链表构造函数。构造函数从链表而不是数组构建字符串。另一个文件测试对象以验证它的能力,当我用我的构造函数和toString()方法运行该文件时,我收到此错误:

Running constructor, length, toString tests (10 tests)
Starting tests: ..FF......
Time: 0.00

2 failures:
1) t02aEmptyConstructorIsEmptyString(LStringTest$EmptyStringTest)
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
        ... 1 more
        at LString.<init>(LString.java:45)
        at LStringTest$EmptyStringTest.t02aEmptyConstructorIsEmptyString(LStringTest.java:193)
        ... 9 more
2) t02bEmptyConstructorHasZeroLength(LStringTest$EmptyStringTest)
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
        ... 1 more
        at LString.<init>(LString.java:45)
        at LStringTest$EmptyStringTest.t02bEmptyConstructorHasZeroLength(LStringTest.java:198)
        ... 9 more

Test Failed! (2 of 10 tests failed.)

我相信我正在构建链接列表,并且错误地创建了LString对象,尽管我很难找到原因。任何建议都值得赞赏,试图学习java。

这是我的代码:

public class LString    {

     node front;
     int size;

     private class node {
          char data;
          node next;

          public node (){
          }

          public node (char newData){
                this.data = newData;
          }

          public node (char newData, node newNext){
                this.data = newData;
                this.next = newNext;
          }


     }

     public LString(){
          this.size =   0;
          this.front =  null;
     }
     public LString(String original)    {
          this.size = original.length();
          this.front =  new node(original.charAt(0));
          node curr = this.front;

          for   (int i =1; i <  original.length(); i++) {
                curr.next = new node(original.charAt(i));
                curr = curr.next;

          }


     }
    public String toString(){
        StringBuilder result = new StringBuilder();

        node curr = front;
        while (curr != null){

            result.append(curr.data);
            curr = curr.next;
        }
        return result.toString();
    }
}

1 个答案:

答案 0 :(得分:2)

将空字符串传递给第二个构造函数时会发生这种情况。在这种情况下,以下行会引发异常。

this.front =  new node(original.charAt(0));

因为chatAt(0)不存在(0超出界限)。您可以使用if条件来保护此构造函数以防止出现这种情况。