Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays An array is a collection of variables, all of the same type. An array is created with the new operator. The size of an array must be specified at.

Similar presentations


Presentation on theme: "Arrays An array is a collection of variables, all of the same type. An array is created with the new operator. The size of an array must be specified at."— Presentation transcript:

1 Arrays An array is a collection of variables, all of the same type. An array is created with the new operator. The size of an array must be specified at creation time. The memory for an array is allocated in a contiguous block. The size of an array is fixed.

2 Array indexing A variable in an array is accessed using special syntax. –Suppose Object[] x = new Object[4]; –Variables: x[0], x[1], x[2] and x[3] –Index ranges from 0 to size-1.

3 Generics You’ve seen how to use generic collections in CSE115. We’ll discuss later how to define them – don’t sweat these details now.

4 Collection interface We’ll set up our Bag implementation to implement the java.util.Collection interface. Method signatures come from this interface. We will not look at all the required methods today, only the four identified earlier: –add, remove, contains and size

5 public class Bag implements Collection { private final static int DEFAULT_CAPACITY = 10; private E[] _store; private int _size; public Bag() { this(DEFAULT_CAPACITY); } public Bag(int initialCapacity) { if (initialCapacity < 1) { initialCapacity = DEFAULT_CAPACITY; } _store = (E[]) new Object[initialCapacity]; _size = 0; }

6 public boolean add(E obj) { if (_size == _store.length) { resize(); } _store[_size] = obj; _size++; return true; }

7 public boolean remove(Object obj) { for (int i = 0; i < _size; i++) { if (_store[i] == obj) { _size--; _store[i] = _store[_size]; _store[_size] = null; return true; } return false; }

8 public boolean contains(Object obj) { for (int i = 0; i < _size; i++) { if (_store[i] == obj) { return true; } return false; }

9 public int size() { return _size; }


Download ppt "Arrays An array is a collection of variables, all of the same type. An array is created with the new operator. The size of an array must be specified at."

Similar presentations


Ads by Google