Java 具有初始值的链表构造函数

Java 具有初始值的链表构造函数,java,arrays,constructor,linked-list,nodes,Java,Arrays,Constructor,Linked List,Nodes,我在做一个链表项目,我和构造器有很大的麻烦 我已经实现了默认构造函数(创建空列表。AKA data=null,size=0),但是另一个构造函数真的让我困惑 我想实现一个构造函数,它创建一个包含值/元素的链表(字符串[])。我的第一个想法是“小菜一碟,我所要做的就是: 使用默认构造函数创建空链表 在for循环中的每个循环使用for。 for each循环的作用是迭代字符串数组并将它们添加到我的空链表中。 需要for循环来跟踪索引。” 这是我的密码: public LinkedList(Str

我在做一个链表项目,我和构造器有很大的麻烦

我已经实现了默认构造函数(创建空列表。AKA data=null,size=0),但是另一个构造函数真的让我困惑

我想实现一个构造函数,它创建一个包含值/元素的链表(字符串[])。我的第一个想法是“小菜一碟,我所要做的就是:

  • 使用默认构造函数创建空链表
  • 在for循环中的每个循环使用for。 for each循环的作用是迭代字符串数组并将它们添加到我的空链表中。 需要for循环来跟踪索引。”
这是我的密码:

public LinkedList(String[] data)
{
    LinkedList l = new LinkedList();

    for (int i = 0; i <= data.length; i++)
    {

        for (String d : data)
        {
            l.add(d, i);
            i++;
        }

    }
}
公共链接列表(字符串[]数据) { LinkedList l=新建LinkedList();
对于(inti=0;i您需要将参数更改为add方法,它希望索引是第一个参数。请参阅


另一种方法是在循环中添加
l.add(d)
,这样可以保证新元素插入到列表的末尾


当我想在给定位置插入时,我会使用
l.add(I,d)

在你编写的构造函数中,你不再真正提到“this”。你创建了一个链表l并修改了它,但你从来没有真正处理过“this”。另外,我同意其他人的观点,第二个for循环是不必要的

这还允许您使用
This()
,这是一个很酷的了解功能。有助于您保持代码的干爽和无bug

public LinkedList(String[] data){
    this(); //Call the default constructor to set up default properties
    for (String d : data){
        add(d); //Call on this
    }
}
你的课程是否扩展?如果是,我会这样做:

public class MyLinkedList extends LinkedList<String> {

    ...

    public MyLinkedList(String... array) {
        super();
        if (array != null && array.length > 0) {
            for (String s : array) {
                add(s);
            }
        }
    }

    ...

}
公共类MyLinkedList扩展LinkedList{
...
公共MyLinkedList(字符串…数组){
超级();
if(array!=null&&array.length>0){
for(字符串s:数组){
添加(s);
}
}
}
...
}
扩展LinkedList不是一个好主意。如果您想要一种使用元素创建新LinkedList的简单方法,请使用以下方法:

public static <E> LinkedList<E> newLinkedList(
        @SuppressWarnings("unchecked") final E... elements) {
    final LinkedList<E> list = new LinkedList<E>();
    Collections.addAll(list, elements);
    return list;
}

....

LinkedList<String> yourList = newLinkedList("foo", "bar", "baz");
公共静态链接列表newLinkedList(
@SuppressWarnings(“未选中”)最终(E…元素){
最终LinkedList=新LinkedList();
Collections.addAll(列表、元素);
退货清单;
}
....
LinkedList yourList=newLinkedList(“foo”、“bar”、“baz”);

您是否遇到了一些异常?它不起作用实际上是什么意思?为什么需要两个循环?@sol4me Yes man,我应该使用this();而不是使用实际的constructor@PM77-1我创建了一个字符串数组,然后使用代码创建了一个链表,然后尝试查找(get方法)和检查(size方法)我需要两个循环来跟踪索引并遍历数组。这是完全正确的,但我的API编写者将add方法描述为public void add(java.lang.String data,int index)。参数是data-then-index。先生,你应该给我一品脱你最喜欢的啤酒。我对“this”非常熟悉函数,事实上,我已经通过我的大多数(90%)其他方法使用了它。但正如我之前所说的“我看不见它”谢谢你(即使我修复了它,我也必须处理其他“新生”的bug)。
public static <E> LinkedList<E> newLinkedList(
        @SuppressWarnings("unchecked") final E... elements) {
    final LinkedList<E> list = new LinkedList<E>();
    Collections.addAll(list, elements);
    return list;
}

....

LinkedList<String> yourList = newLinkedList("foo", "bar", "baz");