Embed presentation
Download to read offline
![Given the following class declaration, write the code in Java for the add function: public class
ArrayList {Private Object []a; Public ArrayList() {a = new Object[10];} public ArrayList(int n)
{a = new Object[n];} public int size() {if[a[0] = = null) return 0; else {int I = 0, count = 0;
while(a[i]! = null){count ++; i++} return count;} public void add(Object n) {
Solution
public void add(Object n)
{
int count = size();
if(count != 0)
{
a[count++] = n; // add the object n to a
}
}](https://image.slidesharecdn.com/giventhefollowingclassdeclaration-writethecodeinjavaforthe-230127182546-8b590101/75/Given-the-following-class-declaration-write-the-code-in-Java-for-the-docx-1-2048.jpg)
The document provides a class declaration for an ArrayList in Java, including constructors and a size method. It specifies the structure of an 'add' function to insert an object into the array at the correct position. The code outlines how to handle the addition of a new object while considering the current size of the array.
![Given the following class declaration, write the code in Java for the add function: public class
ArrayList {Private Object []a; Public ArrayList() {a = new Object[10];} public ArrayList(int n)
{a = new Object[n];} public int size() {if[a[0] = = null) return 0; else {int I = 0, count = 0;
while(a[i]! = null){count ++; i++} return count;} public void add(Object n) {
Solution
public void add(Object n)
{
int count = size();
if(count != 0)
{
a[count++] = n; // add the object n to a
}
}](https://image.slidesharecdn.com/giventhefollowingclassdeclaration-writethecodeinjavaforthe-230127182546-8b590101/75/Given-the-following-class-declaration-write-the-code-in-Java-for-the-docx-1-2048.jpg)