CSE-8B / PA5 / Starter / Set.java
Set.java
Raw
//File: Set.java
//Name: Trai Pham
//Date: 02/09/2020
//Course: CSE 8B

/*Extends OrderedDS implements all methods in OrderedDS and DataStructure
classes, and BasicMethods interface

*/

//this class sets elements in a list and is able to sort the elements in the
//list
public class Set extends UnorderedDS{

  private int maxSize;
  private int indexAt;
  private static final String DUPLICATE_ERROR = "Element already exists";
  private static final String MAX_SIZE_ERROR = "Set maximum limit reached";
//default constructor
  public Set(){
    this.maxSize = 0;
    this.indexAt = 0;
    this.array = null;
  }
//set maxsize of array
  public Set(int maxSize){
    if(maxSize < 0){
      this.maxSize = 0;
      this.array = null;
    }
    else{
      this.maxSize = maxSize;
      this.array = new int [this.maxSize];
    }
  }
//deep copy
  public Set(Set s){
    if( s == null){
      this.maxSize = 0;
      this.array = null;
    }
    else {
      this.maxSize = s.maxSize;
      for(int i = 0; i < this.maxSize; i++){
        this.array[i] = s.array[i];
      }
    }
  }

  public void add(int element){
    //Duplicate error
        for(int i = 0; i < this.indexAt; i++){
          if(element == this.array[i]){
            System.out.println(DUPLICATE_ERROR);
            return;
          }
        }
//maxSize error
    if(this.array == null || this.indexAt == this.array.length ||
    this.maxSize ==0){
      System.out.println(MAX_SIZE_ERROR);
      return;
    }
//Starting off the array
    if(this.indexAt == 0){
      this.array[this.indexAt] = element;
      this.indexAt++;
    }
//inputting more elements
    else{
        this.array[this.indexAt] = element;
        this.indexAt++;
    }

  }
//size/length of the array
  public int size(){
    return this.indexAt;
  }
@Override
  public SortedList toSortedList(){
    SortedList b = new SortedList(this.maxSize);
    for(int i = 0; i < this.indexAt; i++){
      b.add(this.array[i]);
    }
    return b;
  }
  public static void main(String[] args){
    Set a = new Set(5);
    // System.out.println(a.array.length); //gives you length of the array
    a.add(13);
    System.out.println(a.array[0]);
    a.add(6);
    System.out.println(a.array[1]);
    a.add(3);
    System.out.println(a.array[2]);
    a.add(3);
    System.out.println(a.array[3]);
    a.add(3);
    System.out.println(a.array[4]);
    a.add(7);
    a.add(9);
    a.add(19);
    a.add(4);
    SortedList p = a.toSortedList();
    p.toString();
    System.out.println(p);
    p.size();
  }
}