SHARE
TWEET

Untitled

a guest Oct 21st, 2019 81 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package io.javasmithy.collections;
  2.  
  3. public class ArrayCollection<T> implements Collection<T>{
  4.     protected T[] items;
  5.     protected int size;
  6.  
  7.     public ArrayCollection(int cap){
  8.         items = (T[]) new Object[cap];
  9.         size = 0;
  10.     }
  11.  
  12.     public ArrayCollection(){
  13.         this(20);
  14.     }
  15.  
  16.     @Override
  17.     public void add(T item) {
  18.         if(item == null || size >= items.length) return;
  19.         items[size] = item;
  20.         size++;
  21.     }
  22.  
  23.     @Override
  24.     public void remove(T item) {
  25.         //find it
  26.         for(int i = 0; i < size; i++){
  27.             if(items[i].equals(item)){
  28.                 items[i] = items[size-1];
  29.                 items[size-1] = null;
  30.                 size--;
  31.                 break;
  32.             }
  33.         }
  34.     }
  35.  
  36.     @Override
  37.     public boolean contains(T item) {
  38.         for(int i = 0; i < size; i++){
  39.             if(items[i].equals(item)){
  40.                 return true;
  41.             }
  42.         }
  43.         return false;
  44.     }
  45.  
  46.     @Override
  47.     public int size() {
  48.         return size;
  49.     }
  50.  
  51.     public String toString(){
  52.         String str = "[";
  53.         for(int i = 0; i < size; i++){
  54.             str += items[i].toString() + " ";
  55.         }
  56.         return str + "]";
  57.     }
  58.  
  59. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top