0

So I got a bit creative and wanted to re-create some methods in Java and I got stuck with add().

My idea is to check first if we need more size then add (if we need).

After that copy the initial array and then shift the indexes and numbers in the array, but I frankly have no idea how to do that so that's why I'm asking here.

9
  • 1
    Why would there be shifting? Commented Apr 15, 2016 at 18:18
  • If you use javap, you can reverse engineer the bytecode: javap -v java.util.ArrayList. That may help you see what it's doing under the covers. Commented Apr 15, 2016 at 18:19
  • 3
    Or you can just look at the source code. Commented Apr 15, 2016 at 18:21
  • @harold Isn't that logical? If I were just to add some element to certain index without shifting the rest I would just overwrite current element, or at least I think so. Commented Apr 15, 2016 at 18:23
  • @brajevicm well.. maybe? You could just change the index though, and not shift the contents Commented Apr 15, 2016 at 18:26

1 Answer 1

4

The logic is as much as this:

public boolean add(E e) {
    ensureCapacity(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

you can see the hole java source code here

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, that's what I needed.

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.