Implementing Deserialization Of Objects?

Jul 16, 2014

Say you have a bunch of animals, `Rat` `Cat` `Dog` and `Fish`, and you want to serialize/deserialize these animals. Each has its own `serialize()` method. That all works fine and good, if you want to save your Cat to a file, you call `Cat.serialize()` and then you write it to a file.

But what about deserializing? Sure, you could save an extra bit of data that states the type of animal, then use reflection to get a static method (say, `deserialize(String serialized)`) and then invoke it. But that's not safe. What if someone creates a new animal 'Rabbit' and doesn't include a `deserialize(String serialized)` method? Sure, you could then just catch the error and ignore the issue, but that seems unclean and bad practice.

You could also create an enum. Each item in the enum must have a `deserialize(String serialized)` method, and the aforementioned piece of data that states the type references the name of its enum item. Problem is, not very adaptable. Enums don't allow for other animals to be added at runtime.

The way I have been solving this issue is mapping the name of the objects against a deserializer object. Basically each animal would have to 'register' itself by entering it's name and deserializer (implements `Deserializer` interface) object into a HashMap. The deserializer object can then be retrieved via the name of the animal at a later time.

My question is, what is the best method to go about implementing deserialization? Also, is the method I have been using good/bad practice?

Finally, if you are wondering why animals would be added at runtime, the reason is because animals might be added by other non accessible parts of the program, or by things such as plugins.

Example of the method I have been using is below.

Animal Interface

Java Code:

public class Animal{
public String serialize();
} mh_sh_highlight_all('java'); Deserializer Interface

[code]....

And when you needed to deserialize:

Java Code:

Deserializer d=AnimalSpecies.getSpeciesDeserializer(serialized.split(AnimalSpecies.DELIMITER)[0]);
if (d!=null){
d.deserialize(serialized);
} mh_sh_highlight_all('java');

What I mean by this is that any serialized Animal must have a way of identifying which animal it is so that it's deserializer can be accessed. This can be worked around by implementing a wrapper that adds this information directly before it is written to a file, and removes it directly before deserialization.

Why not use built in serialization/deserialization? I would like the serialized data to be readable and easily editable.

View Replies


ADVERTISEMENT

Implementing PhoneDirectory Using Simple Array Of DirectoryEntry Objects

Apr 24, 2014

Having supplied an interface the question arises as to how it should be implemented. There are a number of possibilities including the use of an array list or a linked list; however it is perfectly possible, and in fact instructive, to begin by implementing PhoneDirectory using a simple array of DirectoryEntry objects. This approach is illustrated below:

public class ArrayPhoneDirectory implements PhoneDirectory
{
private static final int INIT_CAPACITY = 100;
private int capacity = INIT_CAPACITY;  
// holds telno of directory entries
private int size = 0;
// Array to contain directory entries
 
[Code] ......

Develop a tester class called ArrayPhoneDirectoryTester . As usual all methods in the class being tested should be executed at least once by the test driver. Supply standard test documentation - Test Plan, Test Data and Test Log.

In addition to the methods described in the interface the class ArrayPhoneDirectory contains three private methods listed below:

// Searches the array of directory entries for a specific name
private int find(String name){}
 
// Adds a new entry with the given name and telno to the array of
// directory entries
private void add(String name, String telno){}
 
// Creates a new array of directory entries with twice the capacity
// of the previous one
private void reallocate(){}

These methods can be thought of as "helper" methods in that they assist the work of the public methods of the class. For example, the find() method is used by the lookUpEntry() method to locate the position of the a specific directory entry.

Pseudo-code algorithms for the methods of ArrayPhoneDirectory are listed below

Algorithm for load

create a Scanner to read file
while (not end of file)
use Scanner to read the name
use Scanner to read the telno
create a DirectoryEntry
add the new entry to theDirectory
close file

This method is a good place to start coding but note that load makes use of the add method in case the number of entries stored in the text file has exceeded the initial capacity of the directory. So to implement load fully you will need a working version of the "helper" method add. However you can do this in stages by first developing a basic version of add which does not increase the size of the directory. In reading data from the file you may assume that the file only contains matched pairs of names and numbers. There is no need to consider the case of a name not being associated with a telephone number.

Algorithm for addChangeEntry
call find to see whether name is in directory
if name is in theDirectory
change the telno using setNumber
return the old telno
else
add a new entry to theDirectory using method add
return null

[Code] ....

I don't know how to do any of this at all

View Replies View Related

Hashmap Slower After Deserialization?

Feb 15, 2015

I have a pretty large Hashmap (~250MB). Creating it takes about 50-55 seconds, so I decided to serialize it and save it to a file. Reading from the file takes about 16-17 seconds now.

The only problem is that lookups seems to be slower this way. I always thought that the hashmap is read from the file into the memory, so the performance should be the same compared to the case when I create the hashmap myself, right? Here is the code I am using to read the hashmap into a file:

File file = new File("omaha.ser");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(new BufferedInputStream(f));
omahaMap = (HashMap<Long, Integer>) s.readObject();
s.close();

300 million lookups take about 3.1 seconds when I create the hashmap myself, and about 8.5 seconds when I read the hashmap from file.

View Replies View Related

I/O / Streams :: Deserialization Of Class Object Received Within XML Message

Apr 5, 2014

I receive an XML message (over an HttpURLConnection) that contains a serialized Java object. This is the received XML message:

<?xml version="1.0" encoding="UTF-16"?><Olive><Responses><Character>
aced0005737200116f626a656374732e4368617261637465720000
0000000000000200034c00056974656d737400154c6a6176612f757

[Code] .....

What I want to do is to deserialize the Java object which is contained within the <Character> element. (The first four characters "aced" reveals that we are dealing with serialized content. So far so good.) I'm using this code to grab the characters within <Character> and deserialize them into a Java object:

Node characterElement = responsesElementChildren.item(0); // <Character>
String characterSerialized = characterElement.getTextContent();
ByteArrayInputStream bais = new ByteArrayInputStream( characterSerialized.getBytes() );
ObjectInputStream ins = new ObjectInputStream( bais );
objects.Character retrievedCharacter = (objects.Character) ins.readObject();

However, the above operation fails and I get this exception:

java.io.StreamCorruptedException: invalid stream header: 61636564
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at network.requests.RequestRetrieveCharacter.addResponse(RequestRetrieveCharacter.java:99)
at network.GameServer.ask(GameServer.java:151)
at Client.main(Client.java:43)

I cannot tell if the received serialized data is okay or not, so I really don't know if the problem is here in the deserialization or actually in the serialization (on the sending side where the Java object is serialized and packed into an XML message).

View Replies View Related

Copying Data Objects To Serializable Objects

Jul 27, 2014

I am currently working on a project where I need to return data from a database over RMI to a client who requests it. Some of the fields in the Data Object can not be seen by the client so I need to create another object to send over the network instead. The method I use is this...

public static SerializableObject createSerializableObjectFromDataObject(DataObject dataObject){
SerializableObject serializableObject = new SerializableObject();
serializableObject.setField(dataObject.getField());
serializableObject.setAnotherField(dataObject.getAnotherField());
return serializableObject;
}

Is there a better way of doing this? I am creating many subclasses DataObject which all require this static method to be implemented and I can't push it into the superclass because each one needs custom behaviour.

View Replies View Related

Implementing A FPS Counter

Jan 17, 2014

Ok, so I'm making a game with a space ship that flies around the universe and discovering new planets. It works fine so far, but I'm looking to make it perform better and be better compatible with lesser-processors.So, I'm trying to put in an FPS counter and an entirely new game loop so that my game can decide for me what FPS I should use.

I have two classes. Heres the big, main one: [Java] package cyentw.game.src; import java.awt.Color; import java.awt.Font; impor - Pastebin.com *I want to change the loop and put an FPS counter in around line 456, you can scroll past the rest if you'd like*And heres the init frame one, in case you'd like to see it for some reason.

Java Code:

package cyentw.game.src;
import javax.swing.JFrame;
public class Start extends JFrame{
public static JFrame frame;
public static int WIDTH = 500;
public static int HEIGHT = 500;
public Start() {

[code]....

how to make my game loop as quickly (or a bit slower) as it can, and my FPS is static.

View Replies View Related

Swing/AWT/SWT :: Implementing JTabbedPane GUI?

Aug 21, 2014

I have been trying to learn how to use the TabbedPane GUI. I can get the tabs to show up, but the buttons I have placed in each tab do not show up. Why this is not working. I assume that, for some reason, the buttons are not linking with their respective panels, or the panels are not linking to the respective tabs.

import java.awt.BorderLayout;
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

[Code] ....

View Replies View Related

Implementing Comparator Interface?

Mar 7, 2014

overriding of the compare method.

Here's an example I found:

public class Someone {
String name;
int age;
ArrayList <Someone> listarr = new ArrayList <Someone>();
public Someone(String name1, int age1) {
name = name1;
age = age1;

[code]...

1. In the compare method, what happens when it returns one of the 0, -1, or 1? How does returning such values contribute to the sorting process? How does it take in information (like I know it does through the parameters, but how exactly)?

2. Why do we use the class name for the generics?

View Replies View Related

Implementing Two Stack In One Array?

Jan 5, 2015

is this program correct? for Implementing two Stack in one array. how can i solve it ?

public class Stackation11 {
int max = 10;
int [] array = new int[max];
int top;
int top1;
Stackation11(){

[code]....

View Replies View Related

Implementing Custom Map Interface

Nov 5, 2014

I am supposed to implement a custom Map interface and I'm having some trouble with this method:

// 1. From the interface
/**
* Gives an iterator iterating over the key set from the smallest key that is not less than the key provided.
* @param key the key
* @return the iterator
* @throws NullPointerException if key == null
*/

public Iterator<Key> tailIterator(Key key);

[Code] .....

My implementation is wrong according to a JUnit test. Also, to get a full score this method should have a worst case running time of O(log N), which obviously isn't the case now. (My Map implementation is currently based on binary search in an ordered array, keeping a prallel array for the values).

View Replies View Related

Implementing Breadth First Search

Dec 13, 2014

I have always wanted to program A*, Breath First Search and Depth First Search ever since I took AI. I will only post BFS at the moment but it is only searching the row.

Java Code:

//Breath First Search. The first node passed to it is the start button
void bfs(Mybuttons button){
Queue<Mybuttons> q = new LinkedList<Mybuttons>();
q.add(button);
button.setIcon(button.setButtonToBlueWhileSearched());
button.model.visted=true;

[Code] ....

Output:

Java Code: In while loop
In get Child Node
In get Child Node
In get Child Node
In get Child Node
In while loop
In get Child Node
In get Child Node
In get Child Node
In while loop
In get Child Node
In get Child Node
In while loop
In get Child Node mh_sh_highlight_all('java');

View Replies View Related

Implementing Heap From ArrayList

Nov 25, 2014

in my class is implement a heap and use some of the methods we were provided. The methods I was provided to code and use are "siftDown", "isEmpty" and "heapify". I'm pretty sure the code I have written for "heapify" and "isEmpty" is correct, where I think I am finding fault is the code for my "siftDown". Would you mind taking a look at my code and see why when adding integers to the heap object that I have created in the main code, that they are not being output correctly?

public class Tester {
public static void main(String[] args) {
Heap myHeap = new Heap();
myHeap.insert(9);
myHeap.insert(15);
myHeap.insert(6);
myHeap.insert(4);
myHeap.insert(10);
myHeap.insert(9);
myHeap.insert(3);

[code]....

View Replies View Related

Implementing Collisions In Frogger

Oct 5, 2014

I am building a frogger game and am having some trouble implementing collisions. I've been going off of various different tutorials and it seems like my frogCollisions function should work based off them, but no matter where I place it collisions aren't registering. Here is the frogCollisions function I am trying to use. I don't think it is very efficient to be checking all of the items in my manager class every loop, but can't think of another way to do this with manager classes. You can see my full code on my github if you would like to see the whole project. It's at: URL....

public void frogCollisions() {
for(int i = 0; i < carManager.smSize(); i++) {
if(f.intersects(carManager.smCars.get(i).getRect())){
player.decreaseLives();
System.out.println(player.getLives());
checkGameOver(); // NEED TO IMPLEMENT STILL

[code]....

View Replies View Related

Program For Implementing A Stack

Jan 3, 2015

I tried to write a program to implement a stack but it has a bug I am unable to solve.The bug is that whenever I choose an operation to perform, eg push, After performing the operation, the loop is executed once again and Invalid choice message appears, i.e. the default case. And then the loop again executes to choose further option. Here is my code

class Stack {
private char[] stck;
private int len;
private int top;

[code]....

View Replies View Related

Implementing Inheritance In Java

Apr 25, 2014

i was leaning inheritance and tried to implement it in Java.This is my base class vehicl.java

public class vehicle{
private int topSpeed;
private int cubicCap;
private String modelName;
private boolean hasAlloy;

[code]...

I also have a derived class called car.java.What i wanted to do in the derived class was that i wanted to override the constructor as well as the getInfo() method from the base class.I wanted to add an additional attribute to the car "numberSeats" and display tat too when the object to car class calls the getInfo() method .It showed an error "identifier required" when i tried to compile car.java program.

import java.util.Scanner;
public class car extends vehicle{
//int numberSeats;
//System.out.println("Enter the number of Seats");
Scanner numberSeats=new Scanner(System.in);
numberSeats=numberSeats.nextInt();
//System.out.println(numberSeats.nextInt());

[code]....

explain the errors that i get when i tried to compile car.java without using super keyword or without defining the constructor from the Car class ?

View Replies View Related

Swing/AWT/SWT :: Implementing Listener Of GUI In A Different Class?

Jun 26, 2014

I have two different classes called Login (in the package View) and RegButtonListener (in the package Controller). I want to use the MVC pattern.

Login creates a GUI for login. I used NetBeans GUI Builder to create it.

In the class RegButtonListener there is the code for the click of the buttons, then various listeners of the GUI.

Now I want to close the login frame at the click of a button so I want to use the dispose() method.

If I had all the code (GUI code and code of the listener) in the same file, close the frame would be easy enough to do because this.dispose(). But in my case I have two different classes.

I also have a second problem.

In Login class (in the packege View) I have included the line :

regButton.addActionListener(Controller.RegButtonListener).

However, Netbeans tells me an error "package regButton does not exist. <identifier> expected". Why does he consider regButton a package? How can I fix these two problems?

How do I do then?
 
Below is the code of the two classes.

Login class.
public class Login extends javax.swing.JFrame {
/** Creates new form Login */
public Login() {
initComponents();

[code]....

View Replies View Related

Implementing A Thread-safe Queue

Jul 10, 2014

I have situation where a user can request java server to send a value to an embedded device, and if the device is asleep, that value needs to be stored in a queue until the device wakes up and sends a position to java server, at which point the server checks if there is a value in the queue and if there is, it then sends that value to the device. The maximum size of the queue is 1 for now. And if the user makes continuous requests to java server, the old value is removed and the new value is added.

Initially I was looking into BlockingQueue, but the problem with that is, well, it blocks. queue.put(value) will block if queue is full, and queue.take() will block if queue is empty. I can't have something that blocks. When the device responds to server, server checks if value is in queue, if it is not then the server carries on the rest of its responsibility. Thus, I then entertained ConcurrentLinkedQueue. While queue.offer(value) and queue.poll(); allow you to add and remove values respectively from the queue without blocking, it does not allow you to set a maximum size limit of the queue. My queue must have a maximum size limit and it has to always be the newest value the user submits to the queue (where old values are removed).So this is what I came up with:

Java Code: class Unit {
private List<Integer> cmdQueue;

public Unit(){
cmdQueue = Collections.synchronizedList(new LinkedList<Integer>());

[code]....

I use Collections.synchronizedList, as I do here, do I still need to use synchronize as I did above?

View Replies View Related

Implementing A Java Class Library?

Apr 18, 2014

i have been given a homework assignment where I have to get rid of a stack object I wrote for a program and replace it with the Stack<E> library java offers ie:

public class Stack<E> extends Vector<E> {
public Stack(); // constructor
public Boolean empty();
public E peek();
public E pop();
public E push(E item);
}

my question is do i have to actually write all these methods? Or can i just construct a stack and use the methods?

View Replies View Related

Implementing Try / Catch With BinaryToDecimal Program

Apr 27, 2014

I've been assigned to write a program that will convert binary to decimal that uses the try/catch block. In the program that I have written, I was wondering if it is possible to write an addition catch statement that will present an error if any number other than a 0 or 1 is entered by the user. I have already done this in the binaryToDecimal method, but I am just messing around to see if it is, in fact, possible.

Java Code:

import java.io.IOException;
import java.util.Scanner;
public class BinaryToDecimal {
public static void main(String[] args){
Scanner input = new Scanner(System.in);

[Code] .....

View Replies View Related

Implementing Classes Instead Of Extending To Get Methods?

Sep 20, 2014

Basically I want to make a class called library, but I don't want to make an interface because I actually want to define the methods. I think I can only use abstract classes but not really sure how to use those. But I still have a problem, I want to create a Map that classes implementing Library class have to have in their code, and the Map will be a HashMap with <String, ParentClassHere>, so basically let's say I make a class called Car, implemeing Library to the Car class would create a Map library = new HashMap<String, Car>. Can I do something like this? And also include methods to get values and set values to the library Map?

View Replies View Related

Implementing Singly Linked List

Apr 17, 2015

I am trying to implement a singly linked list. My singly linked list, where I implemented a class named linkedlist, that I defined (this implementation of linkedlist is not the java class linkedlist, it is my own version of linkedlist):

Java Code:

public class SinglyLinkedList<E> implements LinkedList<E> {
public class Node<E> {
public Node<E> next;
public E element;
public Node(E element) {

this.element = element;
}

public Node (E element, Node<E> next) {

[code]...

But when I go to my main method to add into my SinglyLinkedList, it doesn't add anything.

View Replies View Related

Implementing ActionListener On Image Button

Nov 28, 2014

Is there something special about this? I would think not, however all of the buttons in my application work except those with images.Here's an example of one:

Java Code: // Class #1
// All components defined as private initially, used in initComponents() later to build GUI
private JButton btnRock = new JButton();
/** Create the frame. **/
public GameView() {
initComponents(); // Initialize components
} // End of GameView Method
public void initComponents() {
// ROCK BUTTON
btnRock = (JButton) mainController.createIcon("rock");
btnRock.setForeground(new Color(0, 0, 0));
btnRock.setBounds(12, 34, 97, 67);

[code]....

View Replies View Related

Implementing Merge Sort On Given Array

Jun 15, 2014

Merge sort implementation on the given array i listed in the code below. I know Arrays.sort() or Collections.sort() could do the trick but i want to achieve it through merge sort.

import java.util.*;
public class Merge{
public static void main(String[] args){
String[] myStringArray=new String[]{"z","a","z","b","c","e","z","f"
,"g","a","w","d","m" ,"x","a","R"
,"q","r","y","w","j","a","v","z","b"};
}
}

View Replies View Related

Implementing Java Project With Android

Nov 19, 2014

I have a gameengine stil partially in the works for pc made in java, I am attempting a port over to java but certain classes and other fuctions are not available for android that there is in java. this means that my render engine, gameengine and a couple of other clases therefore don't work.

My question is, is there anyway of using the gameengine classes that work into the project so that all i have to do is declare within the engine what i want to export for wheather this is android or java. or importing packages from the game engine project and directly linking with the ability of re-writing the odd few classes that do not work.

View Replies View Related

Implementing A Card Game In JAVA

Apr 19, 2015

I am facing with a JAVA code needed for my assignment.We are implementing a Card Game.. There is a Card Class which i have not included in the code below .We have a Dec class that has various arrays..

privateCard[] masterPack >> Is a master Pack that is initialized once and has all the 52 cards.

private Card[] cards >> Is the array that has the card values from masterPack array.

My problem is :

After I called the Deck object D1, it goes to the Deck COnstrucutor OK.It then populates the values of masterPack as per the allowmasterPack method.Then it stores the values of masterPack into cards array in the init method..I get an exception when line below is executed..

cards[pack * 52 + k]= masterPack[k];

I get a java.lang.NullPointerException error..

public class debug
{
public static void main(String[] args)
{
int pack = 1;
Dec D1;
D1 = new Dec(pack);

[oode]...

View Replies View Related

Implementing Probability Of Event Occurring In Java

Jun 7, 2014

You're given a number between 0 and 1 that corresponds to the probability of an event occurring.

0.7 is 70%, 0.235 is 23.5%, 0 is 0%, etc.

Someone tries to perform the event, but the event only has the given probability of occurring. Run the probability, and then if it's true, run the event. Otherwise don't run the event.

All I know how to do is generate random numbers (kind of), but if you have 0.2245 I really don't see how generating random numbers can efficiently perform that probability.....

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved