jeudi 23 avril 2015

interface Borrowable {
  Date getCheckoutDate();
  Date getDudeDate();
  void setCheckoutDate(Date d);
  void setDudeDate(Date d);
}

next class has all the functions that an arraylist has. I have tested all of them and they work perfectly.

class LibraryCollection<E> {
  ArrayList<E> items = new ArrayList<>();

  public Iterator<E> iterator() {return items.iterator();}
  boolean add(E o) {return items.add(o);}
  boolean addAll(Collection<? extends E> c) {...}
...
.....
......
}

here is where I cannot figure up how to make " T[] getOverDueBooks(Date date)" to return a valid array

class ChechOutCart<E extends Borrowable> extends LibraryCollection<E> {
  ArrayList<E> dueOnSpecificDate = new ArrayList<>();
  ArrayList<E> dueOn = new ArrayList<>();

  <T> T[] getOverDueBooks(Date date) {
    T[] a = (T[]) java.lang.reflect.Array.newInstance(items.getClass().getComponentType(), items.size());
    Borrowable current;
    DVD d;
    Book b;

    for (int i = 0; i < items.size(); i++) {
      current = this.items.get(i);

      if (current instanceof Book) {
        b = (Book) current;
        if (date.after(b.getDudeDate())) {
          dueOn.add(this.items.get(i));
        }
      } else if (current instanceof DVD) {
        d = (DVD) current;
        if (date.after(d.getDudeDate())) {
          dueOn.add(this.items.get(i));
        }
      }
    } 
    return dueOn.toArray(a);
  }
}

in main I have made a cauple of DVD and Book objects and they are fully initialized I have omitted the initialization cause too long. I have put then in myCar

public static void main(String[] args) {
    ChechOutCart<Borrowable> myCar = new ChechOutCart<>();
    Borrowable[] array;

    DVD dvd1 = new DVD();
    DVD dvd2 = new DVD();
    Book book1 = new Book();
    Book book2 = new Book();

    myCar.add(book2);
    myCar.add(dvd1);
    myCar.add(book1);
    myCar.add(dvd2);

    array = myCar.getOverDueBooks(new Date(115, 03, 23));
    System.out.println(array);
}

and the errors that I got

Exception in thread "main" java.lang.NullPointerException
at java.lang.reflect.Array.newArray(Native Method)
at java.lang.reflect.Array.newInstance(Array.java:75)
at labb_part_b.ChechOutCart.getOverDueBooks(LabB_Part_B.java:40)
at labb_part_b.LabB_Part_B.main(LabB_Part_B.java:147)
Java Result: 1

I am new in java any idea that you can give me I will appreciate for ever... thanks





Aucun commentaire:

Enregistrer un commentaire