0

I need to implement the method Customer3.toArray().

Customer3 is the ADT and Linked List Node (which was given to me by the teacher) and we aren't allowed to change. Just implement the toArray() method. To make it simple, I already know that there will be 64 customer objects in the List so I create an array of 64 elements.

I'm not exactly sure how to do this for LinkedLists. I was hoping maybe someone could show me a simple way of converting it.

Code:

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
} //
2
  • Are you allowed to use any pre-defined libraries? A good way to start is to try and figure out the steps first. Could you share your logic so far? Commented Mar 24, 2013 at 3:32
  • Hint: Existing methods show and add have variations of the list traversal logic that might help when trying to pack the array... Commented Mar 24, 2013 at 3:38

1 Answer 1

1

try

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I found out how to do it myself, but your code is slightly neater and I'm thinking it works so I'll choose you as the right answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.