Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Collection
- */
- public interface Collection {
- public void add(Object element);
- public void remove(Object element);
- public boolean isEmpty();
- public boolean contains(Object element);
- public int size();
- public void removeAll(Object e);
- public int frequency(Object e);
- public String toString();
- }
- import java.util.Arrays;
- /**
- * ArrayCollection
- */
- public class ArrayCollection implements Collection{
- private Object[] elementData;
- private int size;
- public ArrayCollection(int c){
- elementData = new Object[c];
- size=0;
- }
- public ArrayCollection(){
- elementData = new Object[0];
- size=0;
- }
- public void add(Object e) {
- if(e == null) throw new IllegalArgumentException();
- ensureCapacity(size+1);
- elementData[size++] = e;
- }
- public int size(){
- return size;
- }
- public boolean isEmpty() {
- return size == 0;
- }
- public boolean contains(Object e) {
- return indexOf(e) != -1;
- }
- public void remove(Object e) {
- int i = indexOf(e);
- if (i != -1) {
- elementData[i] = elementData[--size];
- elementData[size] = null;
- }
- }
- private int indexOf(Object e) {
- for (int i=0; i<size; i++){
- if(elementData[i].equals(e)) return i;
- }
- return -1;
- }
- private void ensureCapacity(int capacity) {
- if (capacity > elementData.length) {
- int s = Math.max(capacity, 2*elementData.length);
- Object[] arr = new Object[s];
- for(int i = 0; i < size; i++)
- arr[i] = elementData[i];
- elementData = arr;
- }
- }
- public void removeAll(Object e) {
- for (int i = 0; i < size; i++) {
- if(elementData[i].equals(e)) remove(elementData[i]);
- }
- }
- public int frequency(Object e) {
- int counter=0;
- for (int i = 0; i < size; i++) {
- if(elementData[i].equals(e)) counter++;
- }
- return counter;
- }
- public String toString() {
- String result = "[";
- for (int i = 0; i < size; i++) {
- result+=elementData[i];
- if(i!=size-1){
- result+=",";
- }
- }
- result+="]";
- return result;
- }
- }
- /**
- * main
- */
- public class main {
- public static void main(String[] args) {
- Collection name = new ArrayCollection();
- name.add("AJ");
- name.add("CK");
- name.add("TJ");
- name.add("CK");
- name.add("MP");
- name.add("GG");
- name.add("AJ");
- name.add("SB");
- name.add("AJ");
- System.out.println(name.toString());
- System.out.println("num AJ: "+name.frequency("AJ"));
- name.removeAll("AJ");
- System.out.println(name.toString());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement