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;
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());
}
}
In class ListVsSetDemo
In class ColoredSquare:
In class LabSerialization:
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
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