SlideShare a Scribd company logo
For this lab you will complete the class MyArrayList by implementing the MyList interface
provided. The implementation you write must use an array of Object, declared like this:
private Object[] theList;
To successfully implement the interface you must provide a non-abstract version of all the
methods in the interface.
Add functionality that ensures only one type of reference can be added to your
list. In other words, make your list "type-safe'.
Create an overloaded constructor in MyArrayList public MyArrayList( Object type). The
constructor parameter will
be used to set the type of reference to be added to the list. Set up a private filed of the same type
as the parameter. You will also instantiate your Object[] in this constructor. Do not change the
default constructor.
In public boolean add(Object toAdd) you will first check the toAdd parameter to ensure it is the
same as
the type you set in the overloaded constructor. If it is then go ahead and add the reference to
your list. If
not then return false and display an error message indicating the method parameter was rejected
due to
incompatible type.
To check the "toAdd" parameter you will have to first have to get the type of class it is (HINT:
look at
Object methods). Next, you will need to check its type against the type you established in the
overloaded constructor (HINT: look at the Class methods).
Finally, provide a driver class that will:
1) create the an instance of MyList and then add references to it. Be sure to try incompatible
types.
2) Check to see if the list is empty.
3) Display the contents of the list.
4) Display the size of the list.
5) Display the first element in the list.
6) Remove the first element in the list.
7) Display the list one final time.
Modify the classes bellow to match the information above:
/**
* MyArrayList - an imlementation of an array list based on a Java array.
*
* @author Colleen
* @version 2013.11.15
*/
public class MyArrayList
{
private Object[] theList; // array of objects
/**
* Constructor - start with an empty array
*/
public MyArrayList()
{
theList = new Object[0];
}
/**
* Adds a new element at the end of the list.
* @param the object to add
* @return true if element successfully added, false if parameter is null
*/
public boolean add(Object toAdd){
return false;
}
/**
* Gets the object at the specified index.
* @param index value of object to get
* @return object at that index
*/
public Object get(int index){
return null;
}
/**
* Removes specified object from list.
* @param index value of object to remove
* @return the object removed
*/
public Object remove(int index) {
return null;
}
/**
* Returns size of the list
* @return number of elements in the list
*/
public int size(){
return 0;
}
/**
* @return true if the list has no elements, false otherwise
*/
public boolean isEmpty(){
return false;
}
}
------------------------------------
/**
* Write a description of interface List here.
*
* @author (your name)
* @version (a version number or a date)
*/
public interface MyList
{
/**
* Adds a new element at the end of the list.
* @param the object to add
* @return true if element successfully added, otherwise false
*/
boolean add(Object toAdd);
/**
* Gets the object at the specified index.
* @param index value of object to get
* @return object at that index
*/
Object get(int index);
/**
* Removes specified object from list.
* @param index value of object to remove
* @return the object removed
*/
Object remove(int index);
/**
* Returns size of the list
* @return number of elements in the list
*/
int size();
/**
* @return true if the list has no elements, false otherwise
*/
boolean isEmpty();
}
Solution
/**
* Write a description of interface List here.
*
* @author (your name)
* @version (a version number or a date)
*/
public interface MyList {
/**
* Adds a new element at the end of the list.
*
* @param the
* object to add
* @return true if element successfully added, otherwise false
*/
boolean add(Object toAdd);
/**
* Gets the object at the specified index.
*
* @param index
* value of object to get
* @return object at that index
*/
Object get(int index);
/**
* Removes specified object from list.
*
* @param index
* value of object to remove
* @return the object removed
*/
Object remove(int index);
/**
* Returns size of the list
*
* @return number of elements in the list
*/
int size();
/**
* @return true if the list has no elements, false otherwise
*/
boolean isEmpty();
}
-----------------------------------------
import java.util.Arrays;
/**
* MyArrayList - an imlementation of an array list based on a Java array.
*
* @author Colleen
* @version 2013.11.15
*/
public class MyArrayList implements MyList {
private Object[] theList; // array of objects
Class c; //type of reference
int size = 0; //size of array
/**
* Constructor - start with an empty array
*/
public MyArrayList() {
theList = new Object[0];
}
public MyArrayList(Object type) {
c = type.getClass(); //initialize the array type
theList = new Object[1]; //initialize the array with size 1
theList[0] = type; //initialize the element in the array
size = size + 1;
}
/**
* Adds a new element at the end of the list.
*
* @param the
* object to add
* @return true if element successfully added, false if parameter is null
*/
public boolean add(Object toAdd) {
if (this.c != null && !(toAdd.getClass().equals(this.c))) {
System.out.println("Incompatible Argument type " + toAdd);
return false;
} else if (this.c == null) {
this.c = toAdd.getClass();
theList = new Object[1];
} else if (toAdd.getClass().equals(this.c)) {
theList = Arrays.copyOf(theList, this.size + 1);
}
this.size = this.size + 1;
theList[this.size - 1] = toAdd;
return true;
}
/**
* Gets the object at the specified index.
*
* @param index
* value of object to get
* @return object at that index
*/
public Object get(int index) {
if (!(this.isEmpty())) {
return theList[index];
} else
return null;
}
/**
* Removes specified object from list.
*
* @param index
* value of object to remove
* @return the object removed
*/
public Object remove(int index) {
Object item = theList[index];
for (int i = index; i < this.size - 1; i++) {
theList[i] = theList[i + 1];
}
this.size = this.size - 1;
theList = Arrays.copyOf(theList, this.size);
System.out.println("Element removed successfully.");
return item;
}
/**
* Returns size of the list
*
* @return number of elements in the list
*/
public int size() {
return size;
}
/**
* @return true if the list has no elements, false otherwise
*/
public boolean isEmpty() {
if (size == 0) {
return true;
}
return false;
}
}
----------------------------------------------------
public class TestClass {
public static void main(String[] args) {
MyList obj = new MyArrayList();
obj.add(1);
obj.add(5);
obj.add(7);
obj.add("test");
obj.add(9);
obj.add(4);
System.out.println("Is this List empty: "+obj.isEmpty());
System.out.println("contents of the list :");
for (int i = 0; i < obj.size(); i++) {
System.out.println(obj.get(i));
}
System.out.println("Size of the List: " + obj.size());
System.out.println("first element in the list: "+obj.get(0));
obj.remove(0);
obj.remove(3);
System.out.println("contents of the list :");
for (int i = 0; i < obj.size(); i++) {
System.out.println(obj.get(i));
}
}
}

More Related Content

Similar to For this lab you will complete the class MyArrayList by implementing.pdf (20)

PPT
L11 array list
teach4uin
 
DOCX
ArrayList.docx
veerendranath12
 
PPTX
ArrayList class and useful methods.pptx
Abid523408
 
PPTX
collection framework.pptx
SoniaKapoor56
 
PDF
Question 1 MiniList collection 20 marks In this question .pdf
abhisheksharmasre
 
DOCX
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
davidwarner122
 
PPTX
Collections - Lists & sets
RatnaJava
 
PDF
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
arshin9
 
PPT
12_-_Collections_Framework
Krishna Sujeer
 
PDF
Java collections
Hamid Ghorbani
 
DOCX
Please complete all the code as per instructions in Java programming.docx
cgraciela1
 
DOCX
Array list
vishal choudhary
 
PDF
Prompt Your task is to create a connected list implementation and .pdf
alsofshionchennai
 
PDF
Write a java class LIST that outputsmainpublic class Ass.pdf
ebrahimbadushata00
 
PPTX
arraylist in java a comparison of the array and arraylist
PriyadharshiniG41
 
PPTX
arraylistinjava.pptx
dintakurthigayathri9
 
PDF
A popular implementation of List is ArrayList- Look up how to instanti.pdf
arsarees
 
PPT
Collection Framework.power point presentation.......
Betty333100
 
DOCX
Java collections notes
Surendar Meesala
 
PPTX
Collection implementation classes - Arraylist, linkedlist, Stack
RajalakshmiS74
 
L11 array list
teach4uin
 
ArrayList.docx
veerendranath12
 
ArrayList class and useful methods.pptx
Abid523408
 
collection framework.pptx
SoniaKapoor56
 
Question 1 MiniList collection 20 marks In this question .pdf
abhisheksharmasre
 
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
davidwarner122
 
Collections - Lists & sets
RatnaJava
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
arshin9
 
12_-_Collections_Framework
Krishna Sujeer
 
Java collections
Hamid Ghorbani
 
Please complete all the code as per instructions in Java programming.docx
cgraciela1
 
Array list
vishal choudhary
 
Prompt Your task is to create a connected list implementation and .pdf
alsofshionchennai
 
Write a java class LIST that outputsmainpublic class Ass.pdf
ebrahimbadushata00
 
arraylist in java a comparison of the array and arraylist
PriyadharshiniG41
 
arraylistinjava.pptx
dintakurthigayathri9
 
A popular implementation of List is ArrayList- Look up how to instanti.pdf
arsarees
 
Collection Framework.power point presentation.......
Betty333100
 
Java collections notes
Surendar Meesala
 
Collection implementation classes - Arraylist, linkedlist, Stack
RajalakshmiS74
 

More from fashiongallery1 (20)

PDF
Discuss the character and impact of the economic and legal revouluti.pdf
fashiongallery1
 
PDF
Discrete Math -Use induction to prove. The city of Inductionapolis.pdf
fashiongallery1
 
PDF
Describe polarization and why it is important to WLANs.Solution.pdf
fashiongallery1
 
PDF
Describe the four basic elements of most communication systems.So.pdf
fashiongallery1
 
PDF
Can someone please help me figure out how to do this Required Resou.pdf
fashiongallery1
 
PDF
Assume that the Current Assets for Shine Co. as of Decebmer 31, 2011.pdf
fashiongallery1
 
PDF
All computer are configured for TCPIP connectivity. This exercise i.pdf
fashiongallery1
 
PDF
4. At what temperature will a solution of 8.27 g CaCl2 in 45.0 g H2.pdf
fashiongallery1
 
PDF
Briefly Explain all these points belowA. Marketing channels VS cha.pdf
fashiongallery1
 
PDF
Write a class that implements the BagInterface. BagInterface should .pdf
fashiongallery1
 
PDF
write an equation for the transformation of the graph of y =f(x) tra.pdf
fashiongallery1
 
PDF
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
fashiongallery1
 
PDF
Why are helper T-cells called helper cellsThey help pathogens i.pdf
fashiongallery1
 
PDF
Which of the following is NOT true of the Sons of Liberty a. New Yor.pdf
fashiongallery1
 
PDF
What made the Later Roman Economy so unstable (Bennette, Medieval E.pdf
fashiongallery1
 
PDF
What data would illustrate whether these underlying problems are occ.pdf
fashiongallery1
 
PDF
1. What are distinct characteristics of baby boomers, generation X, .pdf
fashiongallery1
 
PDF
VERSION The cells denoted by the letter Ain the figure to.pdf
fashiongallery1
 
PDF
Using standard libraries like stdio and sdtlib.h and using stats.h a.pdf
fashiongallery1
 
PDF
The __________ is the preeminent organization for developing and pub.pdf
fashiongallery1
 
Discuss the character and impact of the economic and legal revouluti.pdf
fashiongallery1
 
Discrete Math -Use induction to prove. The city of Inductionapolis.pdf
fashiongallery1
 
Describe polarization and why it is important to WLANs.Solution.pdf
fashiongallery1
 
Describe the four basic elements of most communication systems.So.pdf
fashiongallery1
 
Can someone please help me figure out how to do this Required Resou.pdf
fashiongallery1
 
Assume that the Current Assets for Shine Co. as of Decebmer 31, 2011.pdf
fashiongallery1
 
All computer are configured for TCPIP connectivity. This exercise i.pdf
fashiongallery1
 
4. At what temperature will a solution of 8.27 g CaCl2 in 45.0 g H2.pdf
fashiongallery1
 
Briefly Explain all these points belowA. Marketing channels VS cha.pdf
fashiongallery1
 
Write a class that implements the BagInterface. BagInterface should .pdf
fashiongallery1
 
write an equation for the transformation of the graph of y =f(x) tra.pdf
fashiongallery1
 
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
fashiongallery1
 
Why are helper T-cells called helper cellsThey help pathogens i.pdf
fashiongallery1
 
Which of the following is NOT true of the Sons of Liberty a. New Yor.pdf
fashiongallery1
 
What made the Later Roman Economy so unstable (Bennette, Medieval E.pdf
fashiongallery1
 
What data would illustrate whether these underlying problems are occ.pdf
fashiongallery1
 
1. What are distinct characteristics of baby boomers, generation X, .pdf
fashiongallery1
 
VERSION The cells denoted by the letter Ain the figure to.pdf
fashiongallery1
 
Using standard libraries like stdio and sdtlib.h and using stats.h a.pdf
fashiongallery1
 
The __________ is the preeminent organization for developing and pub.pdf
fashiongallery1
 
Ad

Recently uploaded (20)

PDF
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PPTX
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPTX
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
Ad

For this lab you will complete the class MyArrayList by implementing.pdf

  • 1. For this lab you will complete the class MyArrayList by implementing the MyList interface provided. The implementation you write must use an array of Object, declared like this: private Object[] theList; To successfully implement the interface you must provide a non-abstract version of all the methods in the interface. Add functionality that ensures only one type of reference can be added to your list. In other words, make your list "type-safe'. Create an overloaded constructor in MyArrayList public MyArrayList( Object type). The constructor parameter will be used to set the type of reference to be added to the list. Set up a private filed of the same type as the parameter. You will also instantiate your Object[] in this constructor. Do not change the default constructor. In public boolean add(Object toAdd) you will first check the toAdd parameter to ensure it is the same as the type you set in the overloaded constructor. If it is then go ahead and add the reference to your list. If not then return false and display an error message indicating the method parameter was rejected due to incompatible type. To check the "toAdd" parameter you will have to first have to get the type of class it is (HINT: look at Object methods). Next, you will need to check its type against the type you established in the overloaded constructor (HINT: look at the Class methods). Finally, provide a driver class that will: 1) create the an instance of MyList and then add references to it. Be sure to try incompatible types. 2) Check to see if the list is empty. 3) Display the contents of the list. 4) Display the size of the list. 5) Display the first element in the list.
  • 2. 6) Remove the first element in the list. 7) Display the list one final time. Modify the classes bellow to match the information above: /** * MyArrayList - an imlementation of an array list based on a Java array. * * @author Colleen * @version 2013.11.15 */ public class MyArrayList { private Object[] theList; // array of objects /** * Constructor - start with an empty array */ public MyArrayList() { theList = new Object[0]; } /** * Adds a new element at the end of the list. * @param the object to add * @return true if element successfully added, false if parameter is null */ public boolean add(Object toAdd){ return false; } /** * Gets the object at the specified index. * @param index value of object to get * @return object at that index */ public Object get(int index){
  • 3. return null; } /** * Removes specified object from list. * @param index value of object to remove * @return the object removed */ public Object remove(int index) { return null; } /** * Returns size of the list * @return number of elements in the list */ public int size(){ return 0; } /** * @return true if the list has no elements, false otherwise */ public boolean isEmpty(){ return false; } } ------------------------------------ /** * Write a description of interface List here. * * @author (your name)
  • 4. * @version (a version number or a date) */ public interface MyList { /** * Adds a new element at the end of the list. * @param the object to add * @return true if element successfully added, otherwise false */ boolean add(Object toAdd); /** * Gets the object at the specified index. * @param index value of object to get * @return object at that index */ Object get(int index); /** * Removes specified object from list. * @param index value of object to remove * @return the object removed */ Object remove(int index); /** * Returns size of the list * @return number of elements in the list */ int size(); /** * @return true if the list has no elements, false otherwise */ boolean isEmpty();
  • 5. } Solution /** * Write a description of interface List here. * * @author (your name) * @version (a version number or a date) */ public interface MyList { /** * Adds a new element at the end of the list. * * @param the * object to add * @return true if element successfully added, otherwise false */ boolean add(Object toAdd); /** * Gets the object at the specified index. * * @param index * value of object to get * @return object at that index */ Object get(int index); /** * Removes specified object from list. * * @param index * value of object to remove * @return the object removed */ Object remove(int index); /**
  • 6. * Returns size of the list * * @return number of elements in the list */ int size(); /** * @return true if the list has no elements, false otherwise */ boolean isEmpty(); } ----------------------------------------- import java.util.Arrays; /** * MyArrayList - an imlementation of an array list based on a Java array. * * @author Colleen * @version 2013.11.15 */ public class MyArrayList implements MyList { private Object[] theList; // array of objects Class c; //type of reference int size = 0; //size of array /** * Constructor - start with an empty array */ public MyArrayList() { theList = new Object[0]; } public MyArrayList(Object type) { c = type.getClass(); //initialize the array type theList = new Object[1]; //initialize the array with size 1 theList[0] = type; //initialize the element in the array size = size + 1; } /** * Adds a new element at the end of the list.
  • 7. * * @param the * object to add * @return true if element successfully added, false if parameter is null */ public boolean add(Object toAdd) { if (this.c != null && !(toAdd.getClass().equals(this.c))) { System.out.println("Incompatible Argument type " + toAdd); return false; } else if (this.c == null) { this.c = toAdd.getClass(); theList = new Object[1]; } else if (toAdd.getClass().equals(this.c)) { theList = Arrays.copyOf(theList, this.size + 1); } this.size = this.size + 1; theList[this.size - 1] = toAdd; return true; } /** * Gets the object at the specified index. * * @param index * value of object to get * @return object at that index */ public Object get(int index) { if (!(this.isEmpty())) { return theList[index]; } else return null; } /** * Removes specified object from list. * * @param index
  • 8. * value of object to remove * @return the object removed */ public Object remove(int index) { Object item = theList[index]; for (int i = index; i < this.size - 1; i++) { theList[i] = theList[i + 1]; } this.size = this.size - 1; theList = Arrays.copyOf(theList, this.size); System.out.println("Element removed successfully."); return item; } /** * Returns size of the list * * @return number of elements in the list */ public int size() { return size; } /** * @return true if the list has no elements, false otherwise */ public boolean isEmpty() { if (size == 0) { return true; } return false; } } ---------------------------------------------------- public class TestClass { public static void main(String[] args) { MyList obj = new MyArrayList(); obj.add(1);
  • 9. obj.add(5); obj.add(7); obj.add("test"); obj.add(9); obj.add(4); System.out.println("Is this List empty: "+obj.isEmpty()); System.out.println("contents of the list :"); for (int i = 0; i < obj.size(); i++) { System.out.println(obj.get(i)); } System.out.println("Size of the List: " + obj.size()); System.out.println("first element in the list: "+obj.get(0)); obj.remove(0); obj.remove(3); System.out.println("contents of the list :"); for (int i = 0; i < obj.size(); i++) { System.out.println(obj.get(i)); } } }