0

I'm writing a class called List which creates an instance variable array of Customers (Customer is just another class that accepts String parameters for a person's name),

i.e private Customer[] data

I'm trying to write an append method that will take a Customer and add it to another List in the main method.

To do this, there seems to be a method called addAll(), but since I'm writing this code by scratch, I can't use this. I looked at the pseudo code though for this method to get a general idea and it converts the Object into an array and then uses arraycopy to append the two lists.

I meant to say, this way makes sense to me, if I were using arrays, but I'm trying to add a Customer object from another list and add them to a list in the main method.

2
  • If you're using an arraycopy then you must be using arrays (not Lists). Please provide more context. Commented May 23, 2015 at 2:35
  • Sorry, I am using List s, I meant that I understand why the pseudo code uses arraycopy, but that I want to understand how to do it without, because I'm not using arraycopy Commented May 23, 2015 at 2:40

1 Answer 1

0

Not sure of what you want, but I think you can implement the append method yourself just as what the arraycopy method do. Here is a simple example

class List { private int size; private Customer[] data; private final static int DEFAULT_CAPACITY = 10; public List() { size = 0; data = new Customer[DEFAULT_CAPACITY]; } public void append(List another) { int anotherSize = another.size; for (int i = anotherSize - 1; i >= 0; --i) { if (size < data.length) { data[size++] = another.data[i]; another.data[i] = null; another.size--; } else { throw new IndexOutOfBoundsException(); } } } } 
Sign up to request clarification or add additional context in comments.

4 Comments

BTW, the source code of ArrayList class is a good reference.
Thanks! Although I don't really get the lines another.data[i] = null; another.size--;, could you give a quick explanation?
@hello Those two lines are used to remove the element which have been taken and added to the base List. If you do not want to remove element as well as take it, you do not need to do that. Sorry for a mistake in the for loop, and I just fixed it.
Right, that makes more sense to remove the elements if you're starting from the end. Okay, thanks again!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.