putting data into array and then JTable - java

Referring to an earlier question i asked
lining up data in console output java
I wish to put my output in an array so that i can then further put this into a JTable
The extract for my code so far is, i am currently printing out the output to the console.
String assd = null;
String eventy = null;
String assdFT = null;
for (int i = 0; i < list.getLength(); i++) {
Element element = (Element)list.item(i);
String nodeName = element.getNodeName();
switch (nodeName) {
case "assd":
assd = element.getChildNodes().item(0).getNodeValue();
break;
case "eventy":
eventy = element.getChildNodes().item(0).getNodeValue();
break;
case "assdFT":
assdFT = element.getChildNodes().item(0).getNodeValue();
break;
System.out.printf("%-30s %-20s %s%n", assd, eventy,assdFT);
Object[][] data = {{assd, eventy,assdFT}};//this only appears to put the elements in row 1, since System.out.println(data[1][0]) causes an out of array exception but System.out.println(data[0][0]) prints out all the elements of assd

To put data directly into a JTable pass an instance of your custom AbstractTableModel to the JTable constructor. Within TableModel, you can define what data is displayed and how it is accessed.
It would probably look something like this:
public class HeaderTableModel extends AbstractTableModel {
/**
*
*/
private static final long serialVersionUID = 8974549762036798969L;
private Object[][] myData;
public HeaderTableModel(final Object[][] theRows) {
myHeaderRows = theRows;
}
/*
* (non-Javadoc)
*
* #see javax.swing.table.TableModel#getColumnCount()
*/
#Override
public int getColumnCount() {
return LocalStorage.getNumColumns();
}
/*
* (non-Javadoc)
*
* #see javax.swing.table.TableModel#getRowCount()
*/
#Override
public int getRowCount() {
return LocalStorage.getNumRows();
}
/*
* (non-Javadoc)
*
* #see javax.swing.table.TableModel#getValueAt(int, int)
*/
#Override
public Object getValueAt(final int theRow, final int theColumn) {
return myHeaderRows[theRow][theColumn];
}

Related

Utilizing delegate pattern for matrices

I implemented a delegate pattern to hide away the linear algebra libraries I wanted to benchmark, according to this, see:
public interface Matrix<M> {
/**
* Cols or this matrix
*
* #return columns
*/
int rows();
/**
* Rows of this matrix
*
* #return rows
*/
int cols();
/**
* Matrix multiplication, should throw if cols and rows do not match.
* Contract is This X in, i.e. this_rows*this_cols X in_cols*in_rows
*
* #param otherMatrix right operand
* #return new matrix multiplied
*/
M multiply(M otherMatrix);
/**
* Multiply each element with this scalar
*
* #param scalar to multiply with
* #return scaled with scalar
*/
M multiply(double scalar);
/**
* Add in to this matrix
*
* #param in right operand
* #return this + in
*/
M add(M in);
/**
* Add in to all elements of this.
*
* #param in scalar operand
* #return this.map(e - > e + in)
*/
M add(double in);
/**
* Subtract in from all elements of this
*
* #param in scalar operand
* #return this.map(e - > e - in);
*/
M subtract(double in);
/**
* Substract in from this matrix
*
* #param in right operand
* #return this[i][j] -= in[i][j]
*/
M subtract(M in);
/**
* Divide all elements by in
*
* #param in scalar operand
* #return in.map(e - > e / in);
*/
M divide(double in);
/**
* Map this matrix to a double, useful for reduce or trace implementations
*
* #param mapping f: This -> double
* #return a double value
*/
double map(Function<M, Double> mapping);
/**
* Map each element with this function
*
* #param mapping f: Double -> Double each element
* #return this.map(e - > mapping ( e));
*/
M mapElements(Function<Double, Double> mapping);
/**
* Sum this matrix over all entries.
*
* #return sum of this
*/
double sum();
/**
* Max of this matrix over all entries.
*
* #return max of this
*/
double max();
/**
* Index along a column of max, should only be used for vectors.
*
* #return index of max
*/
int argMax();
/**
* Transpose this matrix.
*
* #return transpose.
*/
M transpose();
enum MatrixType {
VECTOR, SQUARE
}
}
with this class:
public class UJMPMatrix implements Matrix<UJMPMatrix> {
private org.ujmp.core.Matrix delegate;
public UJMPMatrix(UJMPMatrix in) { this.delegate = in.delegate; }
public UJMPMatrix(org.ujmp.core.Matrix in) { this.delegate = in; }
public int rows() {
return (int) this.delegate.getRowCount();
}
public int cols() {
return (int) this.delegate.getColumnCount();
}
#Override
public UJMPMatrix multiply(UJMPMatrix otherMatrix) {
return new UJMPMatrix(this.delegate.mtimes(otherMatrix.delegate));
}
#Override
public UJMPMatrix multiply(double scalar) {
return new UJMPMatrix(this.delegate.times(scalar));
}
#Override
public UJMPMatrix add(UJMPMatrix in) {
return new UJMPMatrix(this.delegate.plus(in.delegate));
}
#Override
public UJMPMatrix add(double in) {
return new UJMPMatrix(this.delegate.plus(in));
}
#Override
public UJMPMatrix subtract(double in) {
return new UJMPMatrix(this.delegate.minus(in));
}
#Override
public UJMPMatrix subtract(UJMPMatrix in) {
return new UJMPMatrix(this.delegate.minus(in.delegate));
}
#Override
public UJMPMatrix divide(double in) {
return new UJMPMatrix(this.delegate.divide(in));
}
#Override
public double map(Function<UJMPMatrix, Double> mapping) {
return mapping.apply(this);
}
#Override
public UJMPMatrix mapElements(Function<Double, Double> mapping) {
double[][] elements = this.delegate.toDoubleArray();
double[][] out = new double[elements.length][elements[0].length];
for (int i = 0; i < elements.length; i++) {
for (int j = 0; j < elements[0].length; i++) {
out[i][j] = mapping.apply(elements[i][j]);
}
}
return new UJMPMatrix(out, rows(), cols());
}
#Override
public double sum() {
return this.delegate.getValueSum();
}
#Override
public double max() {
return this.delegate.max(Calculation.Ret.NEW, 0).doubleValue();
}
#Override
public UJMPMatrix transpose() {
return new UJMPMatrix(this.delegate.transpose());
}
#Override
public int argMax() {
double[] array = this.delegate.toDoubleArray()[0];
int argMax = -1;
double best = Double.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
if (array[i] > best) {
best = array[i];
argMax = i;
}
}
return argMax;
}
}
However, when I want to use this abstraction, Java tells me that I cannot use any of these methods, because of the wildcard I need (?) to use to declare these matrices:
private void feedForward(final Matrix<? extends Matrix<?>> starter, final List<Matrix<? extends Matrix<?>>> actives) {
Matrix<? extends Matrix<?>> toPredict = starter;
actives.add(toPredict);
for (int i = 0; i < this.totalLayers - 1; i++) {
final Matrix<? extends Matrix<?>> x = this.weights[i].multiply(toPredict).add(this.biases[i]);
// Weights and Biases are also Matrix<? extends Matrix<?>>[].
// error: cannot resolve method multiply(Matrix<capture ? extends Matrix<?>>)
toPredict = this.functions[i + 1].function(x);
actives.add(toPredict);
}
}
Note: In the constructor of the Neural Network I let the caller decide what type of Matrix they want by a simple enum { OJ_ALGO, UJMP }, and call the Factory I implemented to intialise those matrices. The fields of the neural network look like this:
// Weights and biases of the network
private volatile Matrix<? extends Matrix<?>>[] weights;
private volatile Matrix<? extends Matrix<?>>[] biases;
private volatile Matrix<? extends Matrix<?>>[] dW;
private volatile Matrix<? extends Matrix<?>>[] dB;
Question: How do I declare, initialise and utilise the Matrix abstraction I implemented in this neural network library?
Your feedForward method needs a generic type to signify that both arguments must be of the same type (note the <M> before void) :
private <M> void feedForward(final Matrix<M> starter, final List<M> actives) {
And likewise your neural network class should declare the type of matrices it is using (assuming you don't want to use different implementations at the same time):
public class NeuralNetwork<M> {
private volatile Matrix<M>[] weights;
private volatile Matrix<M>[] biases;
private volatile Matrix<M>[] dW;
private volatile Matrix<M>[] dB;
As a side note, I'm not sure why these are declared as volatile.
Your interface should look like this:
public interface Matrix<M> {
Matrix<M> multiply(Matrix<M> otherMatrix);
M delegate();
And your implementation:
public class UJMPMatrix implements Matrix<org.ujmp.core.Matrix> {
private org.ujmp.core.Matrix delegate;
#Override
public UJMPMatrix multiply(Matrix<org.ujmp.core.Matrix> otherMatrix) {
return new UJMPMatrix(this.delegate.mtimes(otherMatrix.delegate()));
}
#Override
public org.ujmp.core.Matrix delegate() {
return delegate();
}

Is it possible to separate the jtable model to 5 different models?

I create my table model and now i want to seperate it and show it in different JTables. What is the best way to do that?
Here is what i tried :
public List<DefaultTableModel> getProcedures(JPanel panel) {
Object[] data = new Object[blueprint.size()];
Object[] dur = new Object[blueprint.size()]
Object[] status = new Object[blueprint.size()];
List<DefaultTableModel> parralelList = new ArrayList<DefaultTableModel>();
int counter = 0;
for (Object i : blueprint.keySet()) {
data[counter] = blueprint.get(i);
int intDuration = Math.round(blueprintparse.getDuration(i.toString()));
dur[counter] = Integer.toString(intDuration) + "min";
status[counter] = dScreen.fillTableStatus(data[counter].toString());
counter++;
}
parralelList.add(seperateworkFlows(data, dur, status));
return parralelList;
}
private DefaultTableModel seperateworkFlows(Object[] data, Object[] dur, Object[] status) {
DefaultTableModel listModel = new DefaultTableModel();
listModel.addColumn("Procedures", data);
listModel.addColumn("Duration", dur);
listModel.addColumn("Status", status);
return listModel;
}
...
DefaultTableModel model1 = execution.getProcedures(jProgressFlow1).get(0);
jTableFlow1.setModel(model1);
The blueprint is from parsing a json file so from there i am getting the data, duration and status.
Now i want to seperate the model that i created to 5 models under some condition that are inside the json file but at first place i want to hear your opinion also, if the approach is correct.
Thank you very much for your time
Here is my approach.
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
/**
* Table model which allows to split another table model in 2 table models.
*
* #author smedvynskyy
*/
public class SplitTableModel implements TableModel, TableModelListener {
/** Delegate table model. */
private final TableModel delegate;
/** Column index used to split the model. */
private final int splitColumn;
/**
* Part of table to represent (leading [0, {#link #splitColumn}), or trailing [{#link #splitColumn}, delegate.getColumnCount() -
* splitColumn)).
*/
private final boolean leading;
private final Collection<TableModelListener> listeners = new LinkedHashSet<>();
/**
* Instantiates a new split table model.
*
* #param delegate the delegate model to split.
* #param splitColumn the split position (column).
* #param leading defines the part of table to represent (leading: [0, {#link #splitColumn}), or trailing: [{#link #splitColumn},
* delegate.getColumnCount() - splitColumn)).
*/
public SplitTableModel(TableModel delegate, int splitColumn, boolean leading) {
this.delegate = delegate;
this.splitColumn = splitColumn;
this.leading = leading;
delegate.addTableModelListener(this);
}
/**
* Splits the table model in 2 table models.
*
* #param toSplit table model to be split.
* #param splitColumn split column.
* #return array of two models which split the given one (first is the left model, second is the right).
*/
public static TableModel[] split(TableModel toSplit, int splitColumn) {
return new TableModel[] {new SplitTableModel(toSplit, splitColumn, true), new SplitTableModel(toSplit, splitColumn, false)};
}
#Override
public int getRowCount() {
return delegate.getRowCount();
}
#Override
public int getColumnCount() {
return leading ? Math.min(splitColumn, delegate.getColumnCount()) : Math.max(0, delegate.getColumnCount() - splitColumn);
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return delegate.getValueAt(rowIndex, toModelColumnIndex(columnIndex));
}
#Override
public void addTableModelListener(TableModelListener l) {
listeners.add(l);
}
#Override
public void removeTableModelListener(TableModelListener l) {
listeners.remove(l);
}
/**
* Gets all the registered listeners (as unmodifiable collection.
*
* #return all the registered listeners.
*/
public Collection<TableModelListener> getModelListeners() {
return Collections.unmodifiableCollection(listeners);
}
#Override
public String getColumnName(int columnIndex) {
return delegate.getColumnName(toModelColumnIndex(columnIndex));
}
#Override
public Class<?> getColumnClass(int columnIndex) {
return delegate.getColumnClass(toModelColumnIndex(columnIndex));
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return delegate.isCellEditable(rowIndex, toModelColumnIndex(columnIndex));
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
delegate.setValueAt(aValue, rowIndex, toModelColumnIndex(columnIndex));
}
#Override
public void tableChanged(TableModelEvent e) {
int col = e.getColumn() == -1 ? e.getColumn() : toSplitColumnIndex(e.getColumn());
TableModelEvent evt = new TableModelEvent(this, e.getFirstRow(), e.getLastRow(), col, e.getType());
listeners.forEach(l -> l.tableChanged(evt));
}
/**
* Gets the delegate table model.
*
* #return delegate table model.
*/
public TableModel getDelegate() {
return delegate;
}
private int toSplitColumnIndex(int columnIndex) {
return leading ? columnIndex : columnIndex - splitColumn;
}
private int toModelColumnIndex(int columnIndex) {
return leading ? columnIndex : columnIndex + splitColumn;
}
}
This class allows to split a table model in two submodels. But you can continue split, and provide split in 5 models. For example, you have a table model with 15 columns:
TableModel myModel = ...;
List<TableModel> resultModels = new ArrayList<>(5);
TableModel[] split = SplitTableModel.split(myModel, 3);
for (int i = 0; i < 4; i++) {
resultModels.add(split[0]);
if (i == 3) {
resultModels.add(split[1]);
} else {
split = SplitTableModel.split(split[1], 3);
}
}

Im having a problem with my iterator reading more than 3 items

So I have looked over this code for the past couple hours and cannot find the bug. Subset takes in an array for 3 String characters and it will read through and print them out fine, but if I add more than three elements it kicks out an arrayoutofbounds exception and I cannot figure out why. I can manually add them in one by one and it will work but thats not the way that the program was designed to work. Im sure the solution is simple but I cannot find it. Any ideas? Thanks so much.
package a02;
import java.util.Iterator;
import edu.princeton.cs.algs4.StdRandom;
/**
*
* #author Danny
*
* #param <Item>
*/
public class RandomizedQueue<Item> implements Iterable<Item> {
private Item[] queue ;
private int size;
/**
* Constructs an empty randomized queue.
*/
public RandomizedQueue() {
queue = (Item[])new Object[1];
size=0;
}
/**
* parameterized constructor for the Iterator class.
* #param array
*/
private RandomizedQueue(Item[] array)
{
int count = 0;
queue = array;
while(queue[count]!=null)
count++;
queue = (Item[])new Object[array.length];
for(int i=0;i<count;i++)
queue[i]=array[i];
size=count;
}
private Item[] getArray() {
return queue;
}
/**
* Checks to see if the queue is empty.
* #return
*/
public boolean isEmpty() {
return size<=0;
}
/**
* Returns the number of items in the queue.
* #return
*/
public int size() {
return size;
}
/**
* Adds an item.
* #param item
*/
public void enqueue(Item item) {
if (item == null)
throw new java.lang.NullPointerException();
if (size == queue.length)
resize(2*queue.length);
queue[size]= item;
size++;
}
/**
* Deletes and returns a random item
* #return
*/
public Item dequeue() {
if (isEmpty())
throw new java.util.NoSuchElementException();
int index = StdRandom.uniform(size);
Item item = queue[index];
if(index == size-1)
queue[index] = null;
else {
queue[index] = queue[size-1];
queue[size-1]=null;
}
size--;
if(size<=queue.length/4)
resize(queue.length/2);
return item;
}
/**
* Returns a random item, but does not delete it.
* #return
*/
public Item sample() {
if (isEmpty())
throw new java.util.NoSuchElementException();
int index = StdRandom.uniform(size);
return queue[index];
}
/**
* Returns an independent iterator over items in random order.
*/
public Iterator<Item> iterator(){
return new RandomizedQueueIterator();
}
/**
*
* #author Danny
*
*/
private class RandomizedQueueIterator implements Iterator<Item>{
RandomizedQueue<Item> rq = new RandomizedQueue<>(queue);
#Override
public boolean hasNext() {
return rq.size()!=0;
}
#Override
public Item next() {
return rq.dequeue();
}
#Override
public void remove() {
throw new java.lang.UnsupportedOperationException();
}
}
/**
* Resizes the queue array by the given size.
* #param d
*/
private void resize(int d) {
Item[] newArray = (Item[]) new Object[d];
for(int i = 0;i<size;i++)
newArray[i]=queue[i];
queue = newArray;
}
/**
* Unit Testing
* #param args
*/
public static void main(String[] args) {
RandomizedQueue<Integer> rq = new RandomizedQueue<>();
rq.enqueue(1);
rq.enqueue(2);
rq.enqueue(3);
rq.enqueue(4);
rq.enqueue(5);
rq.enqueue(6);
rq.enqueue(7);
Iterator<Integer> iterator1 = rq.iterator();
while(iterator1.hasNext())
System.out.println(iterator1.next());
System.out.println();
Iterator<Integer> iterator2 = rq.iterator();
while(iterator2.hasNext())
System.out.println(iterator2.next());
}
}
package a02;
import java.util.Iterator;
public class Subset {
public static void main(String[] args) {
//char [] c = {'b', 'a', 'C'};
String[] c= {"hello", "hi", "howdy", "english"};
RandomizedQueue<String> queue = new RandomizedQueue<String>();
for (int i=0;i<c.length; i++)
queue.enqueue(c[i]);
int k=3;
Iterator<String> iterator=queue.iterator();
for (int i=0; i<k;i++) {
System.out.println(iterator.next());
}
}
}
In the constructor RandomizedQueue(Item[] array) you need to add a bounds check before accessing queue.
Change:
while(queue[count]!=null)
to
while(count < queue.length && queue[count]!=null)

Swap two elements

I wrote a simple easy code to exchange two elemnts in a list, that looks like this:
public void swap(Item a, Item aprev, Item b, Item bprev){
aprev.next = b;
bprev.next = a;
}
Now. If i want to actually swap two elements, nothing really changes. So if I do this:
SelectionSortableList list = new SelectionSortableList();
Item item = list.new Item("4");
Item item1 = list.new Item("5");
Item item2 = list.new Item("6");
Item item3 = list.new Item("7");
list.addFront(item.value);
list.addFront(item1.value);
list.addFront(item2.value);
list.addFront(item3.value);
System.out.println(list.toString());
list.swap(item1, item, item3, item2);
System.out.println(list.toString());
/* */ public abstract class SinglyLinkedList
/* */ {
/* */ protected SinglyLinkedList.Item head;
/* */
/* */ public void addFront(String s) {
/* 6 */ if (head == null) {
/* 7 */ head = new SinglyLinkedList.Item(s);
/* */ }
/* */ else {
/* 10 */ SinglyLinkedList.Item insert = new SinglyLinkedList.Item(s);
/* 11 */ next = head;
/* 12 */ head = insert;
/* */ }
/* */ }
/* */
/* */ public void add(String[] array) { String[] arrayOfString;
/* 17 */ int j = (arrayOfString = array).length;
for (int i = 0; i < j; i++) { String s = arrayOfString[i];
/* 18 */ addFront(s);
/* */ }
/* */ }
/* */
/* */ public String toString()
/* */ {
/* 24 */ if (head == null) {
/* 25 */ return "empty list";
/* */ }
/* 27 */ String s = "";
/* */
/* 29 */ for (SinglyLinkedList.Item helper = head; next != null;
helper = next) {
/* 30 */ s = String.valueOf(s) + value + ", ";
/* */ }
/* 32 */ s = String.valueOf(s) + value;
/* 33 */ return s;
/* */ }
/* */
/* */ public abstract void sort();
/* */
/* */ protected class Item
/* */ {
/* */ public Item next;
/* */ public String value;
/* */
/* */ public Item(String value) {
/* 44 */ this.value = value;
/* */ }
/* */ }
/* */ }
Sorry for that mess, but it is a decompiled jar. And here is my yet unfinished class:
public class SelectionSortableList extends SinglyLinkedList{
public Item head;
public SelectionSortableList(){
this.head = new Item(null);
}
public void swap(Item a, Item aprev, Item b, Item bprev){
aprev.next = b;
bprev.next = a;
}
Nothing changes and he prints me the exact same list, as before. I really have no clue, why this doesn't work.It would be great, if somebody can give me a tip, or maybe if I should write a little bit more. Thank you in beforehand :)
First, it would be good to mention, why you have to or choose to go this way, instead of using a class from the Java Collections Framework.
But even if you do it for educational purposes, e.g. learn about list data structures and algorithms operating on the list, I'd recommend to first program it with the standard Java API, such as in this example.
Then, to understand what's going on inside, follow the source of the used classes. You'll find it at the OpenJDK project or for example nicely browsable here.
When having understood that, you can go back and implement your own version of it and (if you for example have to) use the given data structure.
Concerning your specific problem - I haven't tried it out (you should do that by debugging as suggested before), but I assume that when extending the class and using the same member variable name, you shadow the base class one and thus don't operate on it. So you should extend functionality, but work on the same data structure.

Serializable inner-class [duplicate]

This question already has answers here:
java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException
(2 answers)
Closed 5 years ago.
I was trying to figure out why my code is throwing a "java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: core.FlightOrder$FlightTicket" exception.
I have class declared as:
public class FlightOrder implements Serializable
that contains a private Set of FlightTickets.
And an inner class declared as:
public class FlightTicket
The solution i read about, was to make the inner class "FlightTicket" a static class, but im not sure thats what I'm supose to do to make my code work properly.
can someone help me figure out whats the right way to approach this problem?
public class FlightTicket
{
/**
* The passenger for this ticket
*/
private Customer passenger;
/**
* passenger's seat
*/
private int seat;
/**
* passenger's row
*/
private int row;
/**
* The passenger's class in the plane
*/
private E_ClassType classType;
/**
* Full constructor
* #param passenger
* #param seat
* #param row
* #param classType
*/
public FlightTicket(Customer passenger, int seat, int row , String classType)
{
this.passenger = passenger;
setSeat(seat);
setRow(row);
setClassType(classType);
}
/**
* Partial constructor
* #param seat
* #param row
*/
public FlightTicket(int seat, int row)
{
setSeat(seat);
setRow(row);
}
//-------------------------------Getters And Setters------------------------------
/**
* seat has to be positive number
* #param seat
*/
public void setSeat(int seat) {
if(seat>0)
this.seat = seat;
}
/**
* row has to be positive number
* #param row
*/
public void setRow(int row) {
if(row>0)
this.row = row;
}
/**
*
* #return classType
*/
public E_ClassType getClassType() {
return classType;
}
public int getSeat(){
return seat;
}
public int getRow(){
return row;
}
/**
* set the class type from the array classType located in Constants.
* if the classType not exists, the default value is Economy.
* #param classType
*/
public void setClassType(String classType) {
for(E_ClassType c : E_ClassType.values())
{
if(c.toString().equals(classType))
{
this.classType = E_ClassType.valueOf(classType);
return;
}
}
this.classType = E_ClassType.Tourists;
}
public FlightOrder getOuterType() {
return FlightOrder.this;
}
/* (non-Javadoc)
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + row;
result = prime * result + seat;
return result;
}
/* (non-Javadoc)
* #see java.lang.Object#equals(java.lang.Object)
*/
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FlightTicket other = (FlightTicket) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (row != other.row)
return false;
if (seat != other.seat)
return false;
return true;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "FlightTicket [passenger=" + passenger + ", seat=" + seat
+ ", row=" + row + ", flight number=" + getFlight().getFlightNumber() + "]";
}
}// ~ END OF Inner Class FlightTicket
Making inner class Serializable will work and this is exactly that you are supposed to do if you want to serialize it together with the outer class. The following code demonstrates:
public class Outer implements Serializable {
class Inner implements Serializable {
int value = 17;
}
Inner inner = new Inner();
public static void main(String[] args) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(out);
Outer obj = new Outer();
obj.inner.value = 22;
oout.writeObject(obj);
Outer r = (Outer) new ObjectInputStream(new ByteArrayInputStream(
out.toByteArray())).readObject();
System.out.println(r.inner.value);
}
}
The output is 22, the value that has been correctly serialized and deserialized from the inner class field.
You just need to implement Serializable interface by all the classes which will be serialized. I mean all classes of instance variables declared in your serializable class should also implement Serializable.
In your case FlightTicket and Customer need implement Serializable.

Categories