Question

In this next example, well build two classes that implement the Cloneable Interface. The QuizTracker class contains an ArrayList of QuizScore objects, and its up to us to build these two classes so that we can make deep copies of QuizTrackers (and share no internal aliases). The key idea here is that to make deep copies of compound objects (or lists of objects), we need to copy (using clone) every object in every list, and even make copies of the list objects (ArrayLists here) themselves (1) Start by building a small QuizScore Class that contains only one data item: an int that corresponds to the score received on the quiz (2) Build a second class, QuizTracker, that contains an ArrayList of QuizScore objects (Array List<QuizScore>) as its only data item a. This is just like an IntList covered previously, but instead of ints well be storing Quiz Scores and instead of arrays we can use an ArrayList here (3) Add getters and setters to QuizScore for the score, and provide an add(QuizScore) method for class QuizTracker (note: once done with (4), return to this step to be sure you add a clone of the QuizScore handed as input to this function to avoid privacy leaks) (4) Implement the Cloneable Interface for the QuizScore class (5) Implement the Cloneable Interface for the QuizTracker class, as well a. This should not use ArrayList.clone(), as this is a shallow copy. b. Instead, to create a copy of a QuizTracker, you must first build a new ArrayList for the copy, and i. For each QuizScore object stored in our list, call clone() on each and add the clone() to the newly created ArrayList in (b) c. In this way, if we make a copy of the container (ArrayList), and all the contents in the container (QuizScores), weve succeeded in producing a deep copy for the QuizTracker class

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Following code is for the Quizscore class. Comments are added at places to explain the process performed.


public class Quizscore implements Cloneable{ //Task 4
   int item; //Task 1
   public int getItem() { // Task 3
       return item;
   }

   public void setItem(int item) {// Task 3
       this.item = item;
   }
  
  
/* The below method is custom made to call the super.clone() method for cloning to take place
   Also clone() is a protected method that it is accessible for all subclasses of particular class.
    So to enable the Quiztracker class to use clone() this custom made method getClone() is created.
it just calls the super.clone() from within and return the cloned value to the caller method.*/
   public Quizscore getClone(){
       try {
           return (Quizscore) super.clone();
       } catch (CloneNotSupportedException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
       return this;
    }

}

Following code is for the Quiztracker class. Comments are added at places to explain the process performed.

import java.util.ArrayList;

public class Quiztracker implements Cloneable{ ////Task 5
   ArrayList<Quizscore> qtracker; // Task 2
   ArrayList<Quizscore> copy_qtracker; // Task 5b
  
   Quiztracker(){
       qtracker=new ArrayList<Quizscore>();
       copy_qtracker=new ArrayList<Quizscore>();
   }
  
   //Task 3
   public void add(Quizscore score){ //Taking in cloned items of Quizscore object
      
       qtracker.add(score);
       copy_qtracker.add(score.getClone()); //Task 5c
   /*Storing items of Cloned Quizscore object to new ArrayList copy_qtracker by calling the
   custom made getClone() method defined in Quizscore class*/
   }

   //The below 2 methods are created to traverse through the MainList qtracker and
   //the Cloned list copy_qtracker

   public void getMainList() {
       // TODO Auto-generated method stub
      
       for(int i=0;i<qtracker.size();i++){
           System.out.print(qtracker.get(i).getItem()+" ");
       }
   }

   public void getCloneList() {
       // TODO Auto-generated method stub
       for(int i=0;i<qtracker.size();i++){
           System.out.print(copy_qtracker.get(i).getItem()+" ");
       }
   }
  
}

Finally below is the Main Class that is created to test the functionalities of the above 2 classes.

public class CloneMain {
  
   public static void main(String[] args){

//Creating 3 Quizscore objects for storage and 1 Quiztracker object
       Quizscore sscore=new Quizscore();
       Quizscore sscore1=new Quizscore();
       Quizscore sscore2=new Quizscore();
       Quiztracker trac=new Quiztracker();
      

        sscore.setItem(381);     
       sscore1.setItem(8481);
       sscore2.setItem(919);
      
       trac.add(sscore);
       trac.add(sscore1);
       trac.add(sscore2);
      
      
       System.out.println("Original List Items");
       trac.getMainList();
      
      
       System.out.println("\nCloned List Items");
       trac.getCloneList();
   }

}

This is the output that is generated in the test run of the Main class

Add a comment
Know the answer?
Add Answer to:
In this next example, we'll build two classes that implement the Cloneable Interface. The QuizTracker class...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • (The interface class-like) Assume you have the Edible interface with its abstract method. Design a class named Animal a...

    (The interface class-like) Assume you have the Edible interface with its abstract method. Design a class named Animal and its two subclasses named Mammal and Dairy. Make Sheep and Bear as subclasses of Mammal and make implement the Edible interface. howToEat() and sound() are the main two methods for all edible classes while sound() is the main method for the non-edible classes. 1. Draw the UML diagram for the classes and the interface 2. Use Arraylist class to create an...

  • Exercise 8 (The interface class-like) Assume you have the Edible interface with its abstract method Design...

    Exercise 8 (The interface class-like) Assume you have the Edible interface with its abstract method Design a class named Animal and its two subclasses named Mammal and Dairy. Make Sheep and Bear as subclasses of Mammal and make Chicken and Cow as subclasses of Dairy. The Sheep and Dairy classes implement the Edible interface. howToEat) and sound() are the main two methods for all edible classes while sound() is the main method for the non-edible classes. 1. Draw the UML...

  • The JCF provides numerous classes that implement the List interface, including LinkedList, ArrayList, and Vector. Write...

    The JCF provides numerous classes that implement the List interface, including LinkedList, ArrayList, and Vector. Write code to show how the JCF class ArrayList and LinkedList are used to maintain a grocery list. Verify List methods such as "add()", get(), "remove()", "isEmpty()" and "size()" by implementing a test program. import java.util.ArrayList; import java.util.Iterator; public class GroceryList { static public void main(String[] args){ ArrayList<String> groceryList = new ArrayList<String>(); Iterator<String> iter;    groceryList.add("apples"); groceryList.add("bread"); groceryList.add("juice"); groceryList.add("carrots"); groceryList.add("ice cream");    System.out.println("Number of items...

  • 10.3 Example. When you first declare a new list, it is empty and its length is...

    10.3 Example. When you first declare a new list, it is empty and its length is zero. If you add three objects—a, b, and c—one at a time and in the order given, to the end of the list, the list will appear as a b c The object a is first, at position 1, b is at position 2, and c is last at position 3.1 To save space here, we will sometimes write a list’s contents on one...

  • Define an interface FarmAnimal that contains two methods: getName() and talk(), each returns a string. Declare...

    Define an interface FarmAnimal that contains two methods: getName() and talk(), each returns a string. Declare an abstract class FarmAnimalBase that implements the interface FarmAnimal. In the class FarmAnimalBase, define a private final instance variable name (type: String), a public constructor that initializes the value of the instance variable name, and a public method getName() that returns the value of the instance variable name. Note that we do not implement the method talk() declared in the interface FarmAnimal, that’s the...

  • Implement the classes in the following class diagram. The Book class implements the Comparable interface. Use impl...

    Implement the classes in the following class diagram. The Book class implements the Comparable interface. Use implements Comparable<Book> in the class definition. Now, all book objects are instances of the java.lang.Comparable interface. Write a test program that creates an array of ten books. 1. Use Arrays.sort( Book[]l books) from the java.util package to sort the array. The order of objects in the array is determined using compareTo...) method. 2. Write a method that returns the most expensive book in the...

  • ONLY NEED THE DRIVER CLASS PLEASE!!! Domain & Comparator Classes: 0.) Design a hierarchy of classes,...

    ONLY NEED THE DRIVER CLASS PLEASE!!! Domain & Comparator Classes: 0.) Design a hierarchy of classes, where the Media superclass has the artistName and the mediaName as the common attributes. Create a subclass called CDMedia that has the additional arrayList of String objects containing the songs per album. Create another subclass called DVDMedia that has the additional year the movie came out, and an arrayList of co-stars for the movie. 1.) The superclass Media will implement Comparable, and will define...

  • JAVA Problem:  Coffee    Design and implement a program that manages coffees. First, implement an abstract class...

    JAVA Problem:  Coffee    Design and implement a program that manages coffees. First, implement an abstract class named Coffee. The Coffee class has three member variables: coffee type, price, and store name. The Coffee class has an abstract method name ingredient. Make sure to add all necessary setters and getters as well as other methods. The class Coffee implements an interface HowToMakeDrink. The interface has the following method: public interface HowToMakeDrink { public void prepare (); } The prepare method will...

  • Problem: Coffee(Java) Design and implement a program that manages coffees. First, implement an abstract class named...

    Problem: Coffee(Java) Design and implement a program that manages coffees. First, implement an abstract class named Coffee. The Coffee class has three member variables: coffee type(does not mention the data type of the variable coffeeType), price, and store name. The Coffee class has an abstract method name ingredient. Make sure to add all necessary setters and getters as well as other methods. The class Coffee implements an interface HowToMakeDrink. The interface has the following method: public interface HowToMakeDrink { public...

  • In the USIntsArrayList Class, implement the USIntsArrayListInterface Interface (which is really just the UnSortedInts Class without...

    In the USIntsArrayList Class, implement the USIntsArrayListInterface Interface (which is really just the UnSortedInts Class without the logic. All you are doing in this class is providing the same functionality as UnSortedInts, but using an ArrayList to hold the data. Document appropriately Thank you, package arrayalgorithms; import java.util.ArrayList; /** * Title UnSorted Ints stored in an Array List * Description: Implement all the functionality of the UnSortedInts * class using an ArrayList * @author Khalil Tantouri */ public class USIntsArrayList...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT