Search code examples
javaarraysred-black-tree

Array as an attribute in a java class?


I have an assignment which consists of several small tasks:

  1. I have to initilize an array and fill it with a 200/400/800 values (each amount - once).
  2. I have to take the array values and put it in a red black tree, with certain conditions that are translated to methods.
  3. Some more tasks.

I could do it all in the main class, however it seems to me I would be better off start a new class - handleArray.

If I start a class such as:

public class handlyArray{
    protected int [] arr = new int[];
}

But if I do that, should I write a "get" and "set" functions to get the array's length?

The problem is that when I make this an error pops up - "Array initilizer expected".

Additional functions I have in the class:

public void fillArray(handleArray arr, int k){
        Random rand=new Random();
        for (int i = 0; i <k ; i++) {
            int value = rand.nextInt(1024);
            arr[i]=value;
        }
    }

- A function that creates Nodes for the redblackTree and inserts them to the tree

Any suggestions for how to build it? Can I build the class with no attributes at all?

Thanks!


Solution

  • I'm wary of this being homework so I'll give you an overview and let you do the specifics.

    Yes you can build a getter and setter in your new class, something like:

    public int[] getArray() {
        return arr;
    }
    
    public void setArray(int[] arr) {
        this.arr = arr; //
    }
    

    As for getting the length, you don't need a method for it as you can just call the above getter and ask it for the length, e.g.

    int arrayLength = handlyArray.getArray().length;
    

    Finally yes you need to set up your array first, if you pass in an initialized array to the setter that will do fine, e.g.

    handlyArray.setArray(new int[] {200, 400, 800});
    

    Good luck, feel free to ask if you require further explanation.