Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 13 of 13

Thread: Using ArrayList

  1. #1
    New to the CF scene
    Join Date
    Apr 2011
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Using ArrayList

    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;
        }
    
    
    }

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,978
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    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.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • #3
    New to the CF scene
    Join Date
    Apr 2011
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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);
    
    
    
                }
        }
    
    }

  • #4
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,978
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    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.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • #5
    New to the CF scene
    Join Date
    Apr 2011
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Still getting underlines.


    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(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);
    
    
    
                }
        }
    
    }

  • #6
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,978
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    Quote Originally Posted by Jkeeb View Post
    Still getting underlines.


    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(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.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • #7
    New to the CF scene
    Join Date
    Apr 2011
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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?

  • #8
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,978
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    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<BookSORT_TITLE_ASC = new Comparator<Book>(){
            public 
    int compare(Book b1Book b2)
            {
                return 
    b1.getTitle().compareTo(b2.getTitle());
            }
        };
        
        public static final 
    Comparator<BookSORT_TITLE_DESC = new Comparator<Book>()
        {
            public 
    int compare(Book b1Book b2)
            {
                return 
    Book.SORT_TITLE_ASC.compare(b2b1);
            }
            
        }; 
    And used with something like so:
    PHP Code:
            ArrayList<Bookal = 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(alBook.SORT_TITLE_ASC);
            
            for (
    Book b al)
            {
                
    System.out.println(b.getTitle());
            }
            
            
    Collections.sort(alBook.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 b1Book 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.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • #9
    New to the CF scene
    Join Date
    Apr 2011
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanks this helps a lot.
    One question though.
    In your example you seem to be only comparing 2 books.
    Code:
    public int compare(Book b1, Book b2)
    I will have more then 2 books that I need to sort through.
    How would I handle this?

  • #10
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,978
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    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.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • #11
    New to the CF scene
    Join Date
    Apr 2011
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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.

  • #12
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,978
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    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.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • #13
    New to the CF scene
    Join Date
    Apr 2011
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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();
        }
    }


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •