如何将自定义LinkedList转换为Object Array

时间:2013-03-24 03:23:18

标签: java arrays data-structures linked-list

我需要实现方法Customer3.toArray()。

Customer3是ADT和链接列表节点(由老师提供给我),我们不允许更改。只需实现toArray()方法。为了简单起见,我已经知道列表中将有64个客户对象,所以我创建了一个包含64个元素的数组。

我不确定如何为LinkedLists执行此操作。我希望也许有人可以告诉我一个转换它的简单方法。

代码:

public class
Customer3
implements java.io.Serializable
{
Customer3 next;
String ID;
String name;
String state;
String salesID;
public Customer3() { 
    ID = null; name = null; state = null; salesID = null; 
    next = null; 
}

public Customer3(String i, String n, String s, String si){ 
    ID = i; 
    name = n; 
    state = s; 
    salesID = si; 
    next = null; 
}
public Customer3 getNext() { return next; }
public String getID() { return ID; }
public String getName() { return name; }
public String getState() { return state; }
public String getSalesID() { return salesID; }
public void setNext(Customer3 n) { next = n; }
public void setName(String n) { name = n; }
public void setState(String s) { state = s; }
public void setSalesID (String si) { salesID = si; }
public String toString() { return ID + " " + name + " " + state + " " + salesID; }
public Customer3 add(Customer3 h) {
if (h == null) return this;
Customer3 temp = h;
while (temp.next != null) // look for the end of the list
temp = temp.next;
temp.next = this; // append the new node to the end
return h;
} // add
public void show() {
System.out.println(this);
if (next != null) next.show();
} // show
public Object [] toArray()
{
Object [] temp=null;
temp = new Object[64];



return temp;
} // toArray
} //

1 个答案:

答案 0 :(得分:0)

public Object[] toArray() {
    int size = 1;
    Customer3 curr = this;
    while (curr.next != null) {
        size++;
        curr = curr.next;
    }
    Object[] arr = new Object[size];
    arr[0] = this;
    for (int i = 1; i < size; i++) {
        arr[i] = ((Customer3)arr[i - 1]).next;
    }
    return arr;
}