Java custom exercise with Collections.sort
I have this class Test
and I have to write code of other classes to pass assertions. What class Test
:
import java.util.*; public class Test { public static void main(String[] args) { Book javabook = new Book("Learn Java",150); Book cbook = new Book("C",120); Book[] books = new Book[] {javabook, cbook}; Library lib = new Library(books); assert(lib.pages() == 270); List l = lib; assert(l.size() == 2); Collections.sort(l); assert(l.get(0) == cbook); assert(l.get(1) == javabook); } }
I started to create Book class, here is my implementation:
public class Book implements Comparable { private String name; private int pages; public Book(String name, int pages) { this.name = name; this.pages = pages; } public int getPages() { return this.pages; } public int compareTo(Object obj) { if(this == obj) return 0; else { Book x = (Book) obj; return this.pages - x.pages; } } }
Then I wrote the Library class:
import java.util.*; public class Library extends ArrayList { ArrayList a; public Library(Book[] b) { a = new ArrayList(b.length); for(int i=0; i<b.length; i++) { a.add(b[i]); } } public int pages() { int p = 0; for(int i=0; i<a.size(); i++) { p += ( (Book) a.get(i) ).getPages(); } return p; } public int size() { return a.size(); } public Object get(int i) { return a.get(i); } }
I think the problem is in the class Library
, it Collections.sort
doesn't seem to work and I cannot pass assertions after calling the sort method on the Test class! I can't figure out what is the problem with my code, can anyone help me?
Remember: I need to make my code to pass assert
s.
I'm not sure about my library implementation to make this line in test work:
List l = lib;
Not sure about extending ArrayList.
PS I know it's better to use generic types, but I shouldn't be using them for this exercise. I don't use them, I get some warnings, I just ignore them.
source to share
Your class implementation is Library
really wrong - shouldn't have a list Book
s, it should be a list Book
- why does it extend ArrayList
:
public class Library extends ArrayList<Book> {
// Note: no additional data members.
// The Library is already a List<Book>:
public Library(Book[] b) {
super(Arrays.asList(b));
}
public int pages() {
int p = 0;
for(int i = 0; i < size(); i++) {
p += get(i).getPages();
}
return p;
}
}
source to share