0

I wrote a working method to insert objects into arrayLists in my SortedArrayList class. The problem is, it sorts by the first letter of the first element of the ArrayList.

I would like to be able to choose how the ArrayList is sorted (e.g. by first letter of the surName or by the number of books in a user object. How do I approach this?

An example of the type of object stored: User(String firstName, String surName, int books)

import java.io.*;
import java.util.Scanner;

public class Driver {

    

    //These SortedArrayLists have been derived from the sorted arraylist class
    public static SortedArrayList<User> sortedUsers = new SortedArrayList<>();

    public static SortedArrayList<Book> sortedBooks = new SortedArrayList<>();


    //This static method checks that input matches records and then sets the loaning user information
    //for the book to be loaned while incrementing the number of books held by the user.
    public static void loanBook(Book book, User user){
        for (Book b : sortedBooks){
            if(b.equals(book)) {

                b.setLoanStatus(true);

                b.setLoaningUser(user);

                break;
            }
        }
        for (User u: sortedUsers){
            if(u.equals(user)){
                u.setNumberOfBooks(u.getNumberOfBooks()+1); //The number of books of a given object is found then incremented by one to create the new value, which is set
                break;

            }
        }
    }


    //This static method checks that input matches records and clears loaning user information
    //for the book to be loaned while lowering the number of books held by the user by 1.
    public static void returnBook(Book book, User user){
        for (Book b : sortedBooks){
            if(b.equals(book)){
                 b.setLoanStatus(false);
                 b.setLoaningUser(null);
                break;
            }

            }
            for (User u: sortedUsers){
                if(u.equals(user)){

                    u.setNumberOfBooks(u.getNumberOfBooks()-1);
                    //The number of books for the object instance of a user in question is decreased since they have returned a book and thus have one less book.

                }
            }

    }

    //This is the main method from which the program starts.
    public static void main(String[] args) throws FileNotFoundException, User.InvalidBookLimitException {

       }


        mainMenu(); //main menu printing method
        char ch = sc.next().charAt(0);
        sc.nextLine();
        while (ch !='f') //the program ends as desired if f is pressed


        { switch(ch){

            case 'b':
                System.out.println("Displaying information about all books in the library: ");
                  //This toString replace method removes unwanted items for a cleaner print of book object information and removes the string description for user's name described in the user toString method.
                System.out.println(sortedBooks.toString().replace("[","").replace("]","").replace("Name: ", ""));

                break;
            case 'u':
                System.out.println("Displaying information about all users");

                System.out.println(sortedUsers.toString().replace("[","").replace("]",""));

                break;

            case 'i':
                System.out.println("Enter the loaning out data. ");

                User user = readNames();

                Book book = readBookName();
                //A book object is created based on user input, then an attempt at altering the
                // relevant object information is made via the loanBook method.
                loanBook(book, user);

                break;
            case 'r':
                System.out.println("Please the details of the book to be returned: ");

                User userReturn = readNames();

                Book bookReturn = readBookName();
                //User input is used to create user and book objects so that a book can be returned
                //by use of the returnBook method, resetting any user information about the book and decreasing the count for number of booksheld by the user.
                returnBook(bookReturn, userReturn);

                break;

            default:  //this case occurs if input does not match any of the switch statement cases.
                System.out.println("Invalid input, please enter f, b, i or r");

        }
        mainMenu();
        ch = sc.next().charAt(0);
            sc.nextLine();
        }

    }
}

The sortedArrayList class: import java.util.ArrayList;

public class SortedArrayList<E extends Comparable<E>> extends ArrayList<E> {

    //This insert method ensures that an object added to an arraylist is added in a sorted order.
    public void insert(E value) {
        if (this.size() == 0){
            this.add(value);
            return; }
        for (int i = 0; i < this.size(); i++) {
            int comparison = value.compareTo((E) this.get(i) );
            if (comparison < 0) {
                this.add(i, value);
                return; }
            if (comparison == 0){
                return; }
        }
        this.add(value);
    }
2
  • 1
    Seems your SortedArrayList don't store duplicates, and keeps the array sorted. Why are you doing this? Java comes with the TreeSet class, which has this exact functionality, is much faster than the code you wrote, and has been extensively tested so it doesn't have all the errors that your code does. Use TreeSet. Commented Dec 14, 2020 at 4:51
  • Search Stack Overflow before posting. Custom sorting a collection of objects based on a property value has been addressed many many times already. Commented Dec 14, 2020 at 6:44

1 Answer 1

2

You could simply use a regular ArrayList (or any kind of built in List) and, after you've added all elements, use Collections.sort(). Here you can guve your list as first parameter and a custom Comparator as a second. For the custom comparator you can provide your desired comparison (surname etc.). This sort is also more efficient than what you are currently using.

Here is the JavaDoc: https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List,%20java.util.Comparator)

Sign up to request clarification or add additional context in comments.

1 Comment

And if you want the list to be continuously sorted as elements are added, instead of deferring the sort until the end, use Collections.binarySearch(list, value) to find where to insert a new element.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.