Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package prove;
- import java.util.Iterator;
- import java.util.NoSuchElementException;
- import edu.princeton.cs.introcs.In;
- import edu.princeton.cs.introcs.StdOut;
- public class DynamicArray<Item> implements Iterable<Item>, IterableCollection<Item> {
- Item[] A;
- int N; // Size of the array each moment. Different from capacity.
- @SuppressWarnings("unchecked")
- DynamicArray() {
- A = (Item[]) new Object[0];
- N = 0;
- }
- public void add(Item s) { // adds to the back
- if (A.length == 0)
- resize(1);
- if (N == A.length) {
- resize(2*A.length);
- StdOut.println("Resized for " + s);
- }
- A[N++] = s;
- }
- public void push_back(Item s) {
- add(s);
- }
- public Item get(int index) throws IndexOutOfBoundsException {
- if (index < 0 || index > N)
- throw new IndexOutOfBoundsException("Index out of bounds!");
- return A[index];
- }
- public void set(int index, Item value) throws IndexOutOfBoundsException {
- if (index < 0 || index > N)
- throw new IndexOutOfBoundsException("Index out of bounds!");
- A[index] = value;
- }
- public int capacity() {
- return A.length;
- }
- public int size() {
- return N;
- }
- public boolean isEmpty() {
- return N == 0;
- }
- public Item pop() {
- Item s = A[--N];
- A[N] = null; // Avoids loitering
- if (N > 0 && N == A.length / 4)
- resize(A.length / 2);
- return s;
- }
- private void resize(int capacity) {
- @SuppressWarnings("unchecked")
- Item[] newArray = (Item[]) new Object[capacity];
- for (int i=0; i < N; ++i) {
- newArray[i] = A[i];
- }
- A = newArray;
- }
- @Override
- public Iterator<Item> iterator() {
- return new DynamicArrayIterator();
- }
- private class DynamicArrayIterator implements Iterator<Item> {
- private int index;
- @Override
- public boolean hasNext() {
- if (index < size() - 1 ) return true;
- return false;
- }
- @Override
- public Item next() {
- if (!hasNext() ) throw new NoSuchElementException();
- return A[++index];
- }
- @Override
- public void remove() {
- throw new UnsupportedOperationException();
- }
- }
- public static void main(String args[]) throws Exception {
- In in = new In("input.txt");
- DynamicArray<String> v = new DynamicArray<String>();
- while (!in.isEmpty()) {
- String s = in.readString();
- v.push_back(s);
- }
- for (String str : v)
- StdOut.print(str);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement