0

I making a dynamic array that using normal array and mimic arraylist. So.... Please help me check if the method is correct. rangeCheck is a boolean method checking if the array is out of bound. rangeCheck contains an outofbound exception.

 public int get(int position)
{
    rangeCheck(position);
    int valuePosition =0;
    for(int count=0;count == position;count++)
    {
        valuePosition = storage[count] ;
    }
    return valuePosition; 
}

For some idiotic reason, I keep thinking inorder to get to some value at some specific index, I have to go in a loop to do it....

3
  • 2
    Your loop doesn't make any sense. What are you trying to accomplish with it? Commented Oct 3, 2012 at 1:00
  • Why dont you use ArrayList? ArrayList's get is O(1) and contains is O(n), thats really the best your solution can hope for so why not just use it? Commented Oct 3, 2012 at 1:15
  • dude... as I said, I using normal array and mimic array list with a growth method... Commented Oct 3, 2012 at 1:41

1 Answer 1

3

how about

public int get(int position)
{
    boolean ok = rangeCheck(position);
    if(! ok)        
        throw new IndexOutOfBoundsException("Your error message");
    return storage[position];
}
Sign up to request clarification or add additional context in comments.

2 Comments

Barely beat me to it, but I would add rangeCheck(position) before the first line of the body.
Maybe throw an exception instead of return some_errorcode? But yes, the idea is the same (+1).

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.