What is the finished code in Java? Exercise File 1. Create an collection and fil
ID: 3717148 • Letter: W
Question
What is the finished code in Java?
Exercise File 1. Create an collection and fill it with 20 random numbers between 1 and 15 (inclusive) Seed the constructor of class Random with the value 13 2. Print the numbers 3. Serialize the collection to a file called Numbers.ser 4. Deserialize the file into a new collection called numberFromFile. Remove all duplicate numbers 5. Print the resulting collection (the one without duplicates) Output: Numbers: [8, 11, 6, 14, 14, 6, 14, 9, 2, 15, 11, 7, 11, 11, 3] Numbers without duplicates: [2, 3, 6, 7, 8, 9, 11, 14, 15]Explanation / Answer
//////////////////////////////////////////////////////////////////////////////////////////////////
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
public class RemoveDuplicates{
@SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException, ClassNotFoundException {
//Created Array Collection for Serialization and Deserialization
List<Integer> Collection = new ArrayList<Integer>();
List<Integer> numberFromFile = new ArrayList<Integer>();
Random rnd = new Random(40);
//Seed the random class with 13
rnd.setSeed(13);
for(int i=0;i<20;i++){
//calling rand function within range 1 to 15(inclusively)....
Collection.add(rnd.nextInt((15 - 1) + 1) + 1);
}
System.out.println("Numbers : "+Collection);
//serialization
FileOutputStream fileOut = new FileOutputStream("Numbers.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(Collection);
out.close();
fileOut.close();
//Deserialization
FileInputStream fileIn = new FileInputStream("Numbers.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
numberFromFile = (List<Integer>) in.readObject();
//Converting List to hashset for removing the Duplicates...
HashSet<Integer> hashset = new HashSet<Integer>(numberFromFile);
System.out.println("Numbers Without Duplicates :"+hashset);
in.close();
fileIn.close();
}
}
Sample OutPut After Running Code :
Numbers : [8, 11, 6, 14, 14, 6, 14, 9, 2, 15, 11, 7, 11, 11, 3, 15, 5, 15, 11, 15]
Numbers Without Duplicates :[2, 3, 5, 6, 7, 8, 9, 11, 14, 15]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.