Results 1 to 6 of 6
Thread: MyArrayList
- 01-31-2012, 12:05 AM #1
Senior Member
- Join Date
- Jan 2012
- Posts
- 210
- Rep Power
- 2
MyArrayList
I'm experimenting with implementation of my own ArrayList class, called MyArrayList.
There is a method called add, and while doing it, wonder if I'm on the right way, or should have different approach?
Java Code:public void add(Object o) { add(size, o); } public void add(int index, Object o) { if (index > size) { System.err.print("Index out of bounds"); System.exit(size - index); } if (size == capacity) { capacity *= 2; stack = Arrays.copyOf(stack, capacity); } if (index != size) { Object[] temp = Arrays.copyOf(stack, size); System.arraycopy(temp, index, stack, index + 1, size - index); } stack[index] = o; size++; }
-
Re: MyArrayList
I'd use exceptions rather than System.err statements.
- 01-31-2012, 12:27 AM #3
Senior Member
- Join Date
- Jan 2012
- Posts
- 210
- Rep Power
- 2
Re: MyArrayList
Wonder how Arrays class don't have method such is arraycopy?
Java Code:public void add(int index, Object o) { try { if (size == capacity) { capacity *= 2; stack = Arrays.copyOf(stack, capacity); } if (index != size) { Object[] temp = Arrays.copyOf(stack, size); System.arraycopy(temp, index, stack, index + 1, size - index); } stack[index] = o; size++; } catch (IndexOutOfBoundsException e) { // } }Last edited by diamonddragon; 01-31-2012 at 12:29 AM.
-
Re: MyArrayList
You will want to check into throwing an exception if something is amiss. :) Perhaps a new Exception class that you've created to go along with this class.
- 01-31-2012, 01:11 AM #5
Senior Member
- Join Date
- Jan 2012
- Posts
- 210
- Rep Power
- 2
Re: MyArrayList
I assume that means I'm on the right way.
-
Re: MyArrayList
I meant something like this:
Then create a class MyArrayListException that extends Exception. You should read the Exceptions section of the tutorials to learn more. This will allow classes that use your class decide what to do if the exception is thrown. The outside classes can exit the program or can try to fix the error.Java Code:public class MyArrayList throws MyArrayListException { public void add(int index, Object o) { if (index > size) { throw new MyArrayListExcetion("index " + index + " is > size"); }


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks