-1

I am making an implementation of the ArrayList class from scratch, using just Object[] and the standard functions. I'm trying to make a "size" method, which returns an int that is the size of the Object[] array.

public class MyArraryList{
Object[] Objects = new Object[0];

public int sizeOf(Object[] o)
{
    int i = 1;
    while(i > 0)
    {
        if()
    }
}

This is what I have so far. In the if statement, I essentially want to check if there's an error along the lines of "index out of range of array". I'm not sure what the syntax for this is. Can someone explain how to do this please? thanks!

1
  • @Jared That other question was on how to find the number of digits in an int. Commented Apr 10, 2016 at 23:27

2 Answers 2

1

You can find the length of an array using

objects.length

It would be possible to write a version of ArrayList where the length of the array is always equal to the size of the list. In this case the size method would just be

public int size() {
    return objects.length;
}

Such a list would be very slow. Because arrays are fixed-length, you would have to create a new array on every addition or removal for this to work.

ArrayList does not work like this. An ArrayList has 2 fields; an Object[] and an int called size. The point is that the length of the array is often higher than the size of the list, because there are unused slots at the end of the array. If you do it this way the size method is just

public int size() {
    return size;
}

The most useful thing you can do is read the source code for ArrayList to see how it works.

I essentially want to check if there's an error along the lines of "index out of range of array"

You can find the length of an array like this:

int length = 0;
try {
    while (true) {
        Object o = objects[length];
        length++;
    }
} catch (ArrayIndexOutOfBoundsException e) {
    // ignore
}

However you should not use exceptions in such a way. They should be reserved for genuinely exceptional situations.

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

Comments

0

you could use a try catch with ArrayIndexOutOfBoundsException e, which was made for these kinds of instances. http://www.tutorialspoint.com/javaexamples/exception_multiple1.htm

Comments

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.