Hi I am trying to use ArrayList and am having some issues.
I want to accept input from the user then send the input to an object then store the objects I create into an ArrayList(which eventually will be sorted).
Here are the two classes I have thus far.
Any input is appreciated thanks!
Code:
package lab3;
import java.util.*;
import java.util.ArrayList;
import javax.swing.*;
public class LibraryBook {
public static final int AMMOUNT_OF_BOOKS = 2;
public static void main(String[] args)
{
ArrayList<Book> booklist = new ArrayList<Book>();
getBooks(booklist);
static public void getBooks(Book booklist)
{
for(int i = 0; i < AMMOUNT_OF_BOOKS; i++)
{
String bookTitle = JOptionPane.showInputDialog("Enter the books title.");
String bookAuthor = JOptionPane.showInputDialog("Enter the books author.");
int bookPagecount = Integer.parseInt(JOptionPane.showInputDialog("Enter the ammount of pages in the book."));
Book book = new Book(bookTitle, bookAuthor, bookPagecount);
booklist.add();
}
}
}
Code:
package lab3;
public class Book {
String bookTitle;
String bookAuthor;
int bookPagecount;
public Book(String title, String author, int pages)
{
bookTitle = title;
bookAuthor = author;
bookPagecount = pages;
}
public void setTitle(String Title)
{
bookTitle = Title;
}
public void setAuthor(String Author)
{
bookAuthor = Author;
}
public void setPagecount(int Pagecount)
{
bookPagecount = Pagecount;
}
public String getTitle()
{
return bookTitle;
}
public String getAuthor()
{
return bookAuthor;
}
public int getPagecount()
{
return bookPagecount;
}
}
You didn't say what your issue is.
I can see a few right off the bat; the LibraryBook definitely won't compile since the main hasn't been completed. Next, the booklist you are passing into the getBooks doesn't match the signature requiring a Book. Next, booklist.add will be useless, you need to pass a book to the booklist.add in order to add it into the collection. And finally, the Book class will need to implement Comparable<Book> in order to use a forced sort order when you do implement the sorting for it.
__________________
As of PHP 5.5, the MySQL library has been officially deprecated. It is recommended to move to either MySQLi or PDO libraries for your mysql connectivity. See here for help choosing which interface you prefer: http://php.net/manual/en/mysqlinfo.api.choosing.php
I am unsure what to pass into getBooks declaration and call to get this to work. I am still new to Java and am learning. Your insight is very helpful.
Code:
package lab3;
import java.util.*;
import java.util.ArrayList;
import javax.swing.*;
public class LibraryBook {
public static final int AMMOUNT_OF_BOOKS = 2;
public static void main(String[] args)
{
ArrayList<Book> bookList = new ArrayList<Book>();
getBooks();
}
static public void getBooks(Book bookList)
{
for(int i = 0; i < AMMOUNT_OF_BOOKS; i++)
{
String bookTitle = JOptionPane.showInputDialog("Enter the books title.");
String bookAuthor = JOptionPane.showInputDialog("Enter the books author.");
int bookPagecount = Integer.parseInt(JOptionPane.showInputDialog("Enter the ammount of pages in the book."));
Book book = new Book(bookTitle, bookAuthor, bookPagecount);
bookList.add(book);
}
}
}
getBooks signature needs to be modified to accept an ArrayList or ArrayList<Book> or wildcarded. Since its bound to book, I'd just give it the ArrayList<Book> for simplicity.
__________________
As of PHP 5.5, the MySQL library has been officially deprecated. It is recommended to move to either MySQLi or PDO libraries for your mysql connectivity. See here for help choosing which interface you prefer: http://php.net/manual/en/mysqlinfo.api.choosing.php
package lab3;
import java.util.*;
import java.util.ArrayList;
import javax.swing.*;
public class LibraryBook {
public static final int AMMOUNT_OF_BOOKS = 2;
public static void main(String[] args)
{
ArrayList<Book> bookList = new ArrayList<Book>();
getBooks();
}
static public void getBooks(ArrayList<Book>)
{
for(int i = 0; i < AMMOUNT_OF_BOOKS; i++)
{
String bookTitle = JOptionPane.showInputDialog("Enter the books title.");
String bookAuthor = JOptionPane.showInputDialog("Enter the books author.");
int bookPagecount = Integer.parseInt(JOptionPane.showInputDialog("Enter the ammount of pages in the book."));
Book book = new Book(bookTitle, bookAuthor, bookPagecount);
bookList.add(book);
}
}
}
package lab3;
import java.util.*;
import java.util.ArrayList;
import javax.swing.*;
public class LibraryBook {
public static final int AMMOUNT_OF_BOOKS = 2;
public static void main(String[] args)
{
ArrayList<Book> bookList = new ArrayList<Book>();
getBooks();
}
static public void getBooks(ArrayList<Book>)
{
for(int i = 0; i < AMMOUNT_OF_BOOKS; i++)
{
String bookTitle = JOptionPane.showInputDialog("Enter the books title.");
String bookAuthor = JOptionPane.showInputDialog("Enter the books author.");
int bookPagecount = Integer.parseInt(JOptionPane.showInputDialog("Enter the ammount of pages in the book."));
Book book = new Book(bookTitle, bookAuthor, bookPagecount);
bookList.add(book);
}
}
}
I don't know what you mean by underlined (an actual compile time error is more useful; IDE's do the work of warning with the underlines).
Signature still isn't valid. Also, just noticed you're not actually giving it anything to work with.
That signature should be public static void getBooks(ArrayList<Book> bookList), and don't forget to add the booklist variable into the argument when its called in the main.
__________________
As of PHP 5.5, the MySQL library has been officially deprecated. It is recommended to move to either MySQLi or PDO libraries for your mysql connectivity. See here for help choosing which interface you prefer: http://php.net/manual/en/mysqlinfo.api.choosing.php
Thanks for the assistance. The ArrayList "books" is now filling with "Book" objects.
I noticed in my book they used the Syntax
Code:
List<Book> books = new ArrayList<Book>();
instead of
Code:
ArrayList<Book> books = new ArrayList<Book>();
What is the difference between these? (List and ArrayList) Is one just for arrays and one can be anything?
Also, I would like to ask the user how they want to sort the books they have entered. They will have three options, sort by title, sort by author, sort by pagecount.
Can you recommend a efficient method of doing this? I believe I might need to create a comparator after googling this question. How do these work?
List is an interface in java, which ArrayList implements (via AbstractList). Using a declared variable of List<Book> allows the use of any inherited class of List to be usable as that variable. This is done through polymorphism and the act of dynamic binding. If you view this link: http://download.oracle.com/javase/6/...util/List.html it will show near the top 'Known implementing classes'. That means that any of those classes are (supposed to be ) guaranteeing that they can use all the methods associated with List. Java is odd in the sense that the List and Collection interfaces do not force a guarantee, rather they implement and throw exceptions from the Abstract* level. This is why some are bizarre, like the Stack class implementing List (list allows the use of indexed additions, which really doesn't make sense for a Stack). The real difference is what you can immediately use:
PHP Code:
ArrayList list = new ArrayList();
list.ensureCapacity(10); // This will work.
List list = new ArrayList();
list.ensureCapacity(10); // I believe this will fail; the List and Collection interfaces do not guarantee an ensureCapacity method
List list = new ArrayList();
((ArrayList)list).ensureCapacity(10); // This *may* work, or may throw a ClassCastException
//...
void printList(List l)
{
for (Object o : l)
{
System.out.println(o);
}
}
List l1 = new ArrayList();
ArrayList l2 = new ArrayList();
printList(l1);
printList(l2);
// The above will work since lists are iterable and both are lists.
Interfaces are the single most powerful tool you can have in an object oriented language like java.
For sorting, with multiple sort types you would use the comparator. Be lazy is fine, you can implement a final anonymous class within your books to allow easy sorting and management (or of course declare standard classes). These must return an int of 0, < 0, or > 0. Done like so (I added this to Book as new members):
PHP Code:
public static final Comparator<Book> SORT_TITLE_ASC = new Comparator<Book>(){
public int compare(Book b1, Book b2)
{
return b1.getTitle().compareTo(b2.getTitle());
}
};
public static final Comparator<Book> SORT_TITLE_DESC = new Comparator<Book>()
{
public int compare(Book b1, Book b2)
{
return Book.SORT_TITLE_ASC.compare(b2, b1);
}
};
And used with something like so:
PHP Code:
ArrayList<Book> al = new ArrayList<Book>();
al.add(new Book("Some book", "", 1));
al.add(new Book("Another book", "", 10));
al.add(new Book("Cat in the hat", "", 49));
Collections.sort(al, Book.SORT_TITLE_ASC);
for (Book b : al)
{
System.out.println(b.getTitle());
}
Collections.sort(al, Book.SORT_TITLE_DESC);
for (Book b : al)
{
System.out.println(b.getTitle());
}
Of course, a simple class is also fine:
PHP Code:
public class SortBookByTitleASC implements Comparator<Book>
{
public int compare(Book b1, Book b2)
{
return b1.getTitle().compareTo(b2.getTitle());
}
}
// invoked now with
Collections.sort(al, new SortBookByTitleASC());
How you get the Comparator is quite irrelevant. I added a desc method as well that is chained to the ASC method and simply reverses the arguments. Strings are easy since the String class already has a compareTo method, numbers are easy since you can simply subtract them. Only custom class types are trickier since you need to choose something that they would deem to sort themselves with.
__________________
As of PHP 5.5, the MySQL library has been officially deprecated. It is recommended to move to either MySQLi or PDO libraries for your mysql connectivity. See here for help choosing which interface you prefer: http://php.net/manual/en/mysqlinfo.api.choosing.php
You never do. The comparators job is to compare one object to another to determine if its considered the same, less than or greater than the other. This is how sorting algorithms work (though there are many many many different algorithms designed for different levels of efficiency to ease). They only compare two items at a time to determine whether one goes before the other.
__________________
As of PHP 5.5, the MySQL library has been officially deprecated. It is recommended to move to either MySQLi or PDO libraries for your mysql connectivity. See here for help choosing which interface you prefer: http://php.net/manual/en/mysqlinfo.api.choosing.php
So am I using the wrong method to accomplish sorting these book objects?
I am confused on how using a comparator could help me if it can only compare two objects.
Nope, not at all. The comparator is what you want (or Comparable, but that is more of a 'one shot' method good for always sorting the same way for example).
When you use Collections.sort, it does so based off of the Comparable of the two objects within the collection. It will iterate the collection and do all the sorting for you, all it needs to know is how to compare two objects together. By default it does so by seeking the Comparable.compareTo method on an object. If it does not have a Comparable interface, I believe it then sorts based on hash id's for the object.
Collections.sort has an overload that allows you to pass a Comparator instead. This is essentially identical to a Comparable except that it takes two objects to compare instead of one to compare against itself (since the Comparator is not actually a class you are interested in, you would use it to handle the Book class). This has the benefit of allowing us multiple ways to sort the collection instead of a single way with the Comparable.
So yes, when you sort you only ever need to compare two objects at a time, so a Comparable or Comparator is really what you need. Perhaps an article will help to explain this (learning sorting algorithms btw is very insightful): http://en.wikipedia.org/wiki/Sorting_algorithm
My personal favorite that I've written (through courses requiring this of course; its impractical to write one otherwise) is the heapsort. But that is a fairly advanced sort, you should look at a more fundamental one such as the bubble or selection sort.
__________________
As of PHP 5.5, the MySQL library has been officially deprecated. It is recommended to move to either MySQLi or PDO libraries for your mysql connectivity. See here for help choosing which interface you prefer: http://php.net/manual/en/mysqlinfo.api.choosing.php
Finally got this working for anybody who is looking at this for a reference.
If anybody has any way I could improve my program let me know!
Code:
package lab3;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.*;
public class LibraryBook {
public static final int AMMOUNT_OF_BOOKS = 3;
// Create ArrayList "books"
// Call getBooks and sortBooks methods.
public static void main(String[] args)
{
ArrayList<Book> books = new ArrayList<Book>();
// prefill array for testing
// books.add(new Book("Jon's Book","Jon",23));
// books.add(new Book("Ben's Book","Ben",25));
// books.add(new Book("Jen's Book","Jen",2));
getBooks(books);
getChoice(books);
printBooks(books);
}
//Get book bookTitle, bookAuthor and bookPagecount from user.
//Add each "Book" object containing bookTitle, bookAuthor, bookPagecount to the ArrayList called "books".
public static void getBooks(ArrayList<Book> books)
{
for(int i = 0; i < AMMOUNT_OF_BOOKS; i++)
{
String bookTitle = JOptionPane.showInputDialog("Enter the books title.");
String bookAuthor = JOptionPane.showInputDialog("Enter the books author.");
int bookPagecount = Integer.parseInt(JOptionPane.showInputDialog("Enter the ammount of pages in the book."));
Book book = new Book(bookTitle, bookAuthor, bookPagecount);
books.add(book);
}
}
//Get users choice of how to sort the books.
public static void getChoice(ArrayList<Book> books)
{
int sortOn = Integer.parseInt(JOptionPane.showInputDialog("How do you want to sort your books?\nEnter '0' to Sort by Title\nEnter '1' to Sort by Author\nEnter '2' to Sort by PageCount\n"));
if(sortOn == 0)
{
Collections.sort(books, new BooksSortByTitle());
}
else if(sortOn == 1)
{
Collections.sort(books, new BooksSortByAuthor());
}
else if(sortOn == 2)
{
Collections.sort(books, new BooksSortByPageCount());
}
}
//Print the user's books in selected order.
public static void printBooks(ArrayList<Book> books)
{
for(Book e: books)
{
System.out.println( e.getTitle() + " " + e.getAuthor() + " " + e.getPagecount());
}
}
}
Code:
package lab3;
public class Book {
String bookTitle;
String bookAuthor;
int bookPagecount;
public Book(String title, String author, int pages)
{
bookTitle = title;
bookAuthor = author;
bookPagecount = pages;
}
public void setTitle(String Title)
{
bookTitle = Title;
}
public void setAuthor(String Author)
{
bookAuthor = Author;
}
public void setPagecount(int Pagecount)
{
bookPagecount = Pagecount;
}
public String getTitle()
{
return bookTitle;
}
public String getAuthor()
{
return bookAuthor;
}
public int getPagecount()
{
return bookPagecount;
}
}
Code:
package lab3;
import java.util.Comparator;
public class BooksSortByTitle implements Comparator<Book>
{
public int compare(Book o1, Book o2)
{
return o1.getTitle().compareTo(o2.getTitle());
}
}
Code:
package lab3;
import java.util.Comparator;
public class BooksSortByAuthor implements Comparator<Book>
{
public int compare(Book o1, Book o2)
{
return o1.getAuthor().compareTo(o2.getAuthor());
}
}
Code:
package lab3;
import java.util.Comparator;
public class BooksSortByPageCount implements Comparator<Book>
{
public int compare(Book o1, Book o2)
{
return o1.getPagecount() - o2.getPagecount();
}
}