2

I am creating a class that has an array, and I want to implement methods add, remove, and replace.

But I don't want to use any built-in internals.

public class MySet {

    public int set[];
    private int size = 0;

    public MySet(int size) {
        this.set = new int[size];
    }

    public boolean add(int item) {
        for (int i = 0; i < this.size(); i++) {
            if (this.set[i] != 0) {
                // add to array
            }
        }
        this.size++;
        return true;
    }

    public int size()
    {
        return this.size;
    }
}

When you initialize an array with a fixed size in Java, each item is equal to 0. The part with if this.set[i] != 0 is where I am stuck to add an item.

Should I use a while loop with pointers? Such as:

public boolean add(int item) {
    int index = 0;
    while (index <= this.size()) {
        if (this.set[index] != 0 || index <= ) {
            // increase pointer
            index++;
    }
    this.set[index] = item;
}

But if I have an array such as [7, 2, 0 , 1] in the list, it won't get the last item in the loop, which I need.

So, how is this usually done?

2
  • 3
    You need to keep track of how many items you currently have. Each time you add increase this value. Each time you delete, decrease this value. Commented Sep 27, 2016 at 20:14
  • I recommend taking a look at how ArrayList is implemented, since this is basically what you are trying to do. You need to watch as the internal array grows and shrinks, and determine when it's time to re-allocate it with more empty space. grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/… Commented Sep 27, 2016 at 20:40

1 Answer 1

5

You should keep the current index for the size of populated elements which looks like you do. When you add the set[size]= item and increment size. Once size hits the preallocated size of your array you need to create a new array with increased size (can pick double the size for example) and copy old array to the new one.

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

2 Comments

This makes sense. How would you suggest I check for duplicates? Iterate through entire array?
Well, why would you can about duplicates if you are trying to implement a dynamic array. Those allow for duplicates. Unless you are going for a set? In that case, you can go through the entire array for O(n) complexity or opt for using some hashing algorithm and implement this that way. Your algorithm would have to get more sophisticated in that case.

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.