Question

In: Computer Science

Download labSerialization.zip and unzip it: ListVsSetDemo.java: package labSerialization; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List;...

Download labSerialization.zip and unzip it:

ListVsSetDemo.java:

package labSerialization;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
* Demonstrates the different behavior of lists and sets.
* Author(s): Starter Code
*/
public class ListVsSetDemo {
private final List<ColoredSquare> list;
private final Set<ColoredSquare> set;

/**
* Initializes the fields list and set with the elements provided.
*
* @param elements
*/
public ListVsSetDemo(ColoredSquare... elements) {
list = new ArrayList<>(Arrays.asList(elements));
set = new HashSet<>(Arrays.asList(elements));
}

/**
* Creates a string that includes all the list elements.
* Each element is followed by a new-line.
*
* @return string of list elements
*/
public String getListElements() {
StringBuilder sb = new StringBuilder();
for (ColoredSquare el : list) {
sb.append(el).append("\n");
}
return sb.toString();
}

/**
* Creates a string that includes all the elements in the set.
* Each element is followed by a new-line.
*
* @return string of set elements
*/
public String getSetElements() {
StringBuilder sb = new StringBuilder();
for (ColoredSquare el : set) {
sb.append(el).append("\n");
}
return sb.toString();
}

/**
* Adds the element <code>el</code> to both the list and the set.
*
* @param el
*/
public void addElement(ColoredSquare el) {
list.add(el);
set.add(el);
}
}

ColoredSquare.java:

package labSerialization;

import java.awt.Color;

/**
* A square that is defined by its size and color.
* Author(s): Starter Code
*/
public class ColoredSquare {
private final int side;
private final Color color;

/**
* Initializes the fields <code>side</code> and <code>color</code>.
* @param s the side length of the square
* @param c the color of the square
*/
public ColoredSquare(int s, Color c) {
side = s;
color = c;
}

/**
* Calculates the area of the square.
*/
public int area() {
return side * side;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((color == null) ? 0 : color.hashCode());
result = prime * result + side;
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof ColoredSquare))
return false;
ColoredSquare other = (ColoredSquare) obj;
if (color == null) {
if (other.color != null)
return false;
} else if (!color.equals(other.color))
return false;
if (side != other.side)
return false;
return true;
}

@Override
public String toString() {
return String.format("side:%d #%02X%02X%02X",
side, color.getRed(), color.getGreen(),
color.getBlue());

}

}

LabSerialization.java:

package labSerialization;

import java.awt.Color;

/**
* LabSerialization demonstrates how to serialize and deserialize
* a custom object that references other objects on the heap.
* Author(s): Starter Code + ........... // fill in your name
*/
public class LabSerialization {
public static void main(String[] args) {
ListVsSetDemo demo = new ListVsSetDemo(
new ColoredSquare(4, Color.RED),
new ColoredSquare(6, Color.BLUE),
new ColoredSquare(4, Color.RED),
new ColoredSquare(8, Color.YELLOW));

displayListAndSet(demo);

};

/**
* Displays the elements of the list and the set.
*/
private static void displayListAndSet(ListVsSetDemo demo) {
System.out.println("List:");
System.out.println(demo.getListElements());
System.out.println("Set:");
System.out.println(demo.getSetElements());
}

}

  • Open the Java project 1410_LABS and drag the unzipped folder (package) labSerialization into the src folder. You might be asked whether the files should be copied or linked. Select "Copy files and folders".
    Run the program. You should get an output similar to this.
    Notice how the list includes two squares of size four but there are no duplicates in the set.
  • In class ListVsSetDemo

    • Implement the interface Serializable from package java.io
    • Notice the warning from Eclipse: have Eclipse auto-generate a serialVersionUID
      Right-click the yellow warning icon > Quick Fix > Add Generated Serial Version ID
      A private static final field of type long is added
  • In class ColoredSquare:

    • Implement interface Serializable.
      All classes whose objects are serialized need to implement the interface Serializable. We don't serialize ColoredSquare explicitly. However, objects of type ColoredSquare are used in ListVsSetDemo. That's why we need to implement the interface Serializable for class ColoredSquare as well.
    • Have Eclipse auto-generate a serialVersionUID
  • In class LabSerialization:

    • Add a method called serialize.
      It has no return value and two parameters: demo of type ListVsSetDemo and filename of type String
      • Use a try-with-resource statement when serializing the ListVsSetDemo instance.
        Save the serialized object in the specified file.
      • In case of an exception, print the message provided by the exception object.
    • In the main method comment out the method call
      displayListAndSet(demo);
      Call the method serialize. As filename pass a relative path that creates the file Demo.ser in the directory labSerialization.
      Print a brief message to let the user know that serialization is complete.
      Run the program and verify that the instance got serialized and that the file got created.
    • Add a method called deserialize.
      It returns a ListVsSetDemo and has one parameter: a filename of type String
      • Use a try-with-resource statement to implement the deserialize method
      • Use a single catch block to catch both IOExceptions and FileNotFoundExceptions
    • In main call the method deserialize.
      Assign the ListVsSetDemo returned to a new variable called newDemo and pass it to the method displayListAndSet

Sample Output

This sample output should give you a good idea of what is expected. Note though, that the elements in HashSet are in no particular order. Because of that, the second part of the output might look slightly different.

Sample Output

List:
side:4 #FF0000
side:6 #0000FF
side:4 #FF0000
side:8 #FFFF00

Set:
side:6 #0000FF
side:8 #FFFF00
side:4 #FF0000

Solutions

Expert Solution

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks

// ListVsSetDemo.java

import java.io.Serializable;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.HashSet;

import java.util.List;

import java.util.Set;

/**

* Demonstrates the different behavior of lists and sets. Author(s): Starter

* Code

*/

public class ListVsSetDemo implements Serializable {

    //auto generated serial version uid

    private static final long serialVersionUID = 1L;

    private final List<ColoredSquare> list;

    private final Set<ColoredSquare> set;

    /**

     * Initializes the fields list and set with the elements provided.

     *

     * @param elements

     */

    public ListVsSetDemo(ColoredSquare... elements) {

        list = new ArrayList<ColoredSquare>(Arrays.asList(elements));

        set = new HashSet<ColoredSquare>(Arrays.asList(elements));

    }

    /**

     * Creates a string that includes all the list elements. Each element is

     * followed by a new-line.

     *

     * @return string of list elements

     */

    public String getListElements() {

        StringBuilder sb = new StringBuilder();

        for (ColoredSquare el : list) {

            sb.append(el).append("\n");

        }

        return sb.toString();

   }

    /**

     * Creates a string that includes all the elements in the set. Each element

     * is followed by a new-line.

     *

     * @return string of set elements

     */

    public String getSetElements() {

        StringBuilder sb = new StringBuilder();

        for (ColoredSquare el : set) {

            sb.append(el).append("\n");

        }

        return sb.toString();

    }

    /**

     * Adds the element <code>el</code> to both the list and the set.

     *

     * @param el

     */

    public void addElement(ColoredSquare el) {

        list.add(el);

        set.add(el);

    }

}

// ColoredSquare.java

import java.awt.Color;

import java.io.Serializable;

/**

* A square that is defined by its size and color. Author(s): Starter Code

*/

public class ColoredSquare implements Serializable {

    private static final long serialVersionUID = 1L;

    private final int side;

    private final Color color;

    /**

     * Initializes the fields <code>side</code> and <code>color</code>.

     *

     * @param s the side length of the square

     * @param c the color of the square

     */

    public ColoredSquare(int s, Color c) {

        side = s;

        color = c;

    }

    /**

     * Calculates the area of the square.

     */

    public int area() {

        return side * side;

    }

    @Override

    public int hashCode() {

        final int prime = 31;

        int result = 1;

        result = prime * result + ((color == null) ? 0 : color.hashCode());

        result = prime * result + side;

        return result;

    }

    @Override

    public boolean equals(Object obj) {

        if (this == obj) {

            return true;

        }

        if (obj == null) {

            return false;

        }

        if (!(obj instanceof ColoredSquare)) {

            return false;

        }

        ColoredSquare other = (ColoredSquare) obj;

        if (color == null) {

            if (other.color != null) {

                return false;

            }

        } else if (!color.equals(other.color)) {

            return false;

        }

        if (side != other.side) {

            return false;

        }

        return true;

    }

    @Override

    public String toString() {

        return String.format("side:%d #%02X%02X%02X", side, color.getRed(),

                color.getGreen(), color.getBlue());

    }

}

// LabSerialization.java

import java.awt.Color;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.util.logging.Level;

import java.util.logging.Logger;

/**

* LabSerialization demonstrates how to serialize and deserialize a custom

* object that references other objects on the heap. Author(s): Starter Code +

* ........... // fill in your name

*/

public class LabSerialization {

    public static void main(String[] args) {

        ListVsSetDemo demo = new ListVsSetDemo(new ColoredSquare(4, Color.RED),

                new ColoredSquare(6, Color.BLUE), new ColoredSquare(4,

                        Color.RED), new ColoredSquare(8, Color.YELLOW));

       

        //serializing demo to "Demo.ser" file

        serialize(demo, "Demo.ser");

        //deserializing it into a new ListVsSetDemo object

        ListVsSetDemo newDemo = deserialize("Demo.ser");

        //passing this new object to displayListAndSet()

        displayListAndSet(newDemo);

    }

    /**

     * Displays the elements of the list and the set.

     */

    private static void displayListAndSet(ListVsSetDemo demo) {

        System.out.println("List:");

        System.out.println(demo.getListElements());

        System.out.println("Set:");

        System.out.println(demo.getSetElements());

    }

    public static void serialize(ListVsSetDemo demo, String filename) {

        //using try with resources, creating an ObjectOutputStream

        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File(filename)))) {

            //writing demo object

            out.writeObject(demo);

            //closing and saving changes

            out.close();

            //letting user know that serialization is complete

            System.out.println("serialization is complete.");

        } catch (IOException ex) {

            //exception occurred.

            System.out.println("Error: " + ex.getMessage());

        }

    }

    public static ListVsSetDemo deserialize(String filename) {

        //initializing a ListVsSetDemo object to null

        ListVsSetDemo data = null;

        //using try with resources, creating an ObjectInputStream

        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(filename)))) {

            //reading ListVsSetDemo object from file to data object

            data = (ListVsSetDemo) in.readObject();

            //closing stream

            in.close();

        } catch (Exception ex) {

            System.out.println("Error: " + ex.getMessage());

        }

        //returning read data

        return data;

    }

}

/*OUTPUT*/

serialization is complete.

List:

side:4 #FF0000

side:6 #0000FF

side:4 #FF0000

side:8 #FFFF00

Set:

side:4 #FF0000

side:6 #0000FF

side:8 #FFFF00


Related Solutions

This is my code I need to complete it? //The code package arraylists; import java.util.ArrayList; import...
This is my code I need to complete it? //The code package arraylists; import java.util.ArrayList; import java.util.Scanner; /** * * */ public class SoftOpening {    public static void main(String[] args) {       Scanner input = new Scanner(System.in);    ArrayList foodList = generateMenu();    User user = generateUser(input); user.introduce();    userBuyFood(foodList, user, input); user.introduce(); } public static ArrayList generateMenu(){    ArrayList foodList = new ArrayList<>();    Food pizza1 =new Food(1,"pizza","Seafood",11,12); Food pizza2 =new Food(2,"pizza","Beef",9,10); Food Friedrice =new Food(3,"fried rice","Seafood",5,12);...
create code for deletestudentbyID Number for choice == 4 package courseecom616; import java.util.Scanner; import java.util.ArrayList; public...
create code for deletestudentbyID Number for choice == 4 package courseecom616; import java.util.Scanner; import java.util.ArrayList; public class CourseeCOM616 {        private String courseName;     private String[] studentsName = new String[1];     private String studentId;        private int numberOfStudents;        public CourseeCOM616(String courseName) {         this.courseName = courseName;     }     public String[] getStudentsName() {         return studentsName;     }     public int getNumberOfStudents() {         return numberOfStudents;     }     public String getStudentId() {         return studentId;    ...
Java: Complete the methods marked TODO. Will rate your answer! -------------------------------------------------------------------------------------------------- package search; import java.util.ArrayList; import...
Java: Complete the methods marked TODO. Will rate your answer! -------------------------------------------------------------------------------------------------- package search; import java.util.ArrayList; import java.util.List; /** * An abstraction over the idea of a search. * * @author liberato * * @param <T> : generic type. */ public abstract class Searcher<T> { protected final SearchProblem<T> searchProblem; protected final List<T> visited; protected List<T> solution; /**    * Instantiates a searcher.    *    * @param searchProblem    *            the search problem for which this searcher will find and   ...
This is the code that needs to be completed... import java.util.ArrayList; import java.util.Collections; /** * Write...
This is the code that needs to be completed... import java.util.ArrayList; import java.util.Collections; /** * Write a description of class SpellChecker here. * * @author (your name) * @version (a version number or a date) */ public class SpellChecker { private ArrayList words; private DictReader reader; /** * Constructor for objects of class SpellChecker */ public SpellChecker() { reader = new DictReader("words.txt"); words = reader.getDictionary(); } /** * This method returns the number of words in the dictionary. * Change...
import java.util.ArrayList; import java.util.Collections; import java.lang.Exception; public class ItemList { /** This is the main process...
import java.util.ArrayList; import java.util.Collections; import java.lang.Exception; public class ItemList { /** This is the main process for the project */ public static void main () { System.out.println("\n\tBegin Item List Demo\n"); System.out.println("Declare an ArrayList to hold Item objects"); ArrayList<Item> list = new ArrayList<Item>(); try { System.out.println("\n Add several Items to the list"); list.add(new Item(123, "Statue")); list.add(new Item(332, "Painting")); list.add(new Item(241, "Figurine")); list.add(new Item(126, "Chair")); list.add(new Item(411, "Model")); list.add(new Item(55, "Watch")); System.out.println("\nDisplay original Items list:"); listItems(list); int result = -1; // 1....
import java.util.ArrayList; import java.util.Collections; import java.lang.Exception; public class ItemList { /** This is the main process...
import java.util.ArrayList; import java.util.Collections; import java.lang.Exception; public class ItemList { /** This is the main process for the project */ public static void main () { System.out.println("\n\tBegin Item List Demo\n"); System.out.println("Declare an ArrayList to hold Item objects"); ArrayList list = new ArrayList(); try { System.out.println("\n Add several Items to the list"); list.add(new Item(123, "Statue")); list.add(new Item(332, "Painting")); list.add(new Item(241, "Figurine")); list.add(new Item(126, "Chair")); list.add(new Item(411, "Model")); list.add(new Item(55, "Watch")); System.out.println("\nDisplay original Items list:"); listItems(list); int result = -1; // 1....
import java.util.ArrayList; import java.util.Collections; public class BirthdayList { /** * This is the main process for...
import java.util.ArrayList; import java.util.Collections; public class BirthdayList { /** * This is the main process for class BirthdayList */ public static void main() { System.out.println("\n\tBegin Birthday List Program\n");    System.out.println("Declare an ArrayList for Birthday objects"); // 1. TO DO: Declare an ArrayList to store Birthday objects (3 Pts)       // 2. TO DO: Replace the xxx.xxxx() with the appropriate method (2 Pts) System.out.printf("\nBirthday List is empty: %s\n", xxx.xxxx() ? "True" : "False");    System.out.println("Add at least five Birthdays to...
This is the class that needs to be written... import java.util.ArrayList; /** * Deals out a...
This is the class that needs to be written... import java.util.ArrayList; /** * Deals out a game of 5-card-stud. * * @author PUT YOUR NAME HERE * @version PUT THE DATE HERE */ public class FiveCardStud { private Deck myDeck; private ArrayList<Hand> players; /** * Constructor for objects of class FiveCardStud */ /* Write a constructor for the FiveCardStud class. The constructor accepts a single integer parameter for the number of players. The number of players should be from 2...
Implement a Factory Design Pattern for the code below: MAIN: import java.util.ArrayList; import java.util.List; import java.util.Random;...
Implement a Factory Design Pattern for the code below: MAIN: import java.util.ArrayList; import java.util.List; import java.util.Random; public class Main { public static void main(String[] args) { Character char1 = new Orc("Grumlin"); Character char2 = new Elf("Therae"); int damageDealt = char1.attackEnemy(); System.out.println(char1.name + " has attacked an enemy " + "and dealt " + damageDealt + " damage"); char1.hasCastSpellSkill = true; damageDealt = char1.attackEnemy(); System.out.println(char1.name + " has attacked an enemy " + "and dealt " + damageDealt + " damage");...
Abstract Cart class import java.util.ArrayList; import java.util.HashMap; /** * The Abstract Cart class represents a user's...
Abstract Cart class import java.util.ArrayList; import java.util.HashMap; /** * The Abstract Cart class represents a user's cart. Items of Type T can be added * or removed from the cart. A hashmap is used to keep track of the number of items * that have been added to the cart example 2 apples or 4 shirts. * @author Your friendly CS Profs * @param -Type of items that will be placed in the Cart. */ public abstract class AbstractCart {...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT