Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: [Beginner] How to add a new object to an object array?

  1. #1
    Junior Member
    Join Date
    Oct 2021
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default [Beginner] How to add a new object to an object array?

    I'm a complete newbie to Java and I want to create a class called Set, where the maximum number of elements of the set is given as parameter in the constructor and the elements of the set are stored in an array of type Book[]. The elements shouldn't exceed the maximum capacity and they should be unique.
    class Set{
        private int maxElements;
        public static int countElements = 0;
        public Book[] arr = new Book[countElements];  
     
        public Set(int maxElements)
        {
            this.maxElements = maxElements;
        }
     
        public boolean addBook(Book b)
        {
            int i = 0, j = 0;
     
          //  if(countElements > maxElements)
            //    return false;
     
            /*for(i = 0; i < countElements; i++)
            {
                if(this.arr[i].getTitle().equals(b.getTitle()))
                    return false;
            }*/
     
            Book[] newArr = new Book[countElements+1];
     
            if (this.arr[0] == null) // if the array is empty
                newArr[0] = this.arr[0];
            else
                for(i = 0; i < countElements; i++)
                {
                    newArr[i] = this.arr[i];
                }
            newArr[countElements] = new Book(b.getTitle(), b.getAuthor());
            countElements++;
     
            // here I want to somehow also return newArr or have newArr replace this.arr as the field
     
            return true;
        }
     
        public void printSet(Book arr[])
        {
            if(arr[0] == null)
            {
                System.out.println("No books in the set.");
            }
            else
            {
                for(int i = 0; i < arr.length; i++)
                {
                    System.out.println("Book ["+i+"] : "+arr[i].getTitle()+" | Author : "+arr[i].getAuthor());
                }
            }
        }
     
        public String toString()
        {
            String res = null;
            for(int i = 0; i < arr.length; i++)
            {
                res = "Book ["+i+"] : "+arr[i].getTitle()+" | Author : "+arr[i].getAuthor();
            }
            return res;
        }
     
        public int getMaxElements()
        {
            return maxElements;
        }
     
    }

    public class SetClient {
        public static void main(String[] args) {
            Set s = new Set(2);
     
     
            Book b1 = new Book("1984", "George Orwell");
            Book b2 = new Book("Hamlet", "William Shakespeare");
     
            s.addBook(b1);
            s.addBook(b2);
     
            /*if(s.addBook(b1) == true)
            {
                System.out.println("Added new book to the set: "+b1.getTitle());
            }
            else
            {
                System.out.println("Book NOT added.");
            }
     
            if(s.addBook(b2) == true)
            {
                System.out.println("Added new book to the set: "+b2.getTitle());
            }
            else
            {
                System.out.println("Book NOT added.");
            }*/
     
     
            System.out.println(s);
        }
     
    }

    class Book{
        private int pages;
        private String title, author;
     
        public Book(int pages)
        {
            this.pages = pages;
        }
     
        public Book(String title, String author)
        {
            this.title = title;
            this.author = author;
        }
     
        public boolean equals(Object book)
        {
            if(book instanceof Book)
            {
                return ((Book)book).pages == this.pages && ((Book)book).title.equals(this.title);
            }
            return false;
        }
     
        public boolean equalsTitle(Object book)
        {
            if(book instanceof Book)
            {
                return ((Book)book).title == this.title;
            }
            return false;
        }
     
        public String toString()
        {
            return "This book has: "+pages+" pages";
        }
     
        public String getTitle()
        {
            return title;
        }
     
        public String getAuthor()
        {
            return author;
        }
    }

    I know this can be solved easier with a list, but I need to use an array. I've changed the addbook and my overall code countless times but I'm never able to add even 1 book. I've looked up a lot of sources and they all make sense but somehow I can't implement a decent solution. What should I change? Currently, I get the following message when running the code:

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
    at Set.addBook(Set.java:26)
    at SetClient.main(SetClient.java:9)

  2. #2
    Member
    Join Date
    Jul 2019
    Posts
    36
    Thanks
    2
    Thanked 4 Times in 4 Posts

    Default Re: [Beginner] How to add a new object to an object array?

    after start arr.length is 0, then can't do
    if (arr[0] == null)
    because [0] doesn't exist

    countElements can't be static in situation of two sets with different length

    public boolean addBook(Book b) {
        Book[] newArr = new Book[countElements +1];
     
        for (int i=0; i < countElements; i++)
             newArr[i] = this.arr[i];
     
        newArr[countElements] = b;
        arr = newArr;
        countElements++;
     
        return true;
      }

Similar Threads

  1. How to add a new object to an object array?
    By rmmstn in forum Collections and Generics
    Replies: 1
    Last Post: December 20th, 2021, 02:12 AM
  2. Want to add an object to an array whilst inheriting another object?
    By lewihenda93 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: October 31st, 2017, 02:30 PM
  3. Replies: 2
    Last Post: September 26th, 2013, 04:13 PM
  4. Beginner : Using a loop to print object array
    By trancecommunity in forum What's Wrong With My Code?
    Replies: 6
    Last Post: February 5th, 2013, 06:31 PM
  5. Reading from ResultSet to Object and from object Object Array
    By anmaston in forum What's Wrong With My Code?
    Replies: 4
    Last Post: April 7th, 2011, 06:11 AM

Tags for this Thread