Utilizing delegate pattern for matrices - java

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();
}

Related

Trying to get an animated object to jump in Java

You are now going to write the various methods in WizardController that animate the wizards. In order to follow the motion of the wizards properly you will need to slow the animation down. To help you do this we have provided a class method delay() in the WizardController class.
WizardController.delay(100);
So the question is write a public class method jump() that returns nothing. It should make the wizard passed as argument jump up one cell position from its current cell then return to its original cell. I have tried the code below and it compiles but not 100% sure if its correct..
public static void jump(Wizard wizard1)
{
wizard1.up();
WizardController.delay(1000);
wizard1.down(1);
}
...also I need to create an instance of wizard and execute the jump() method passing it as argument to check this works as expected. This I am unsure how to do.
here is the full code:
public class WizardController
{
/**
* instance variables
*/
private Wizard wizard1;
private Wizard wizard2;
private int numOfRepeats;
private static final int MIN_NUM_REPEATS = 1;
private static final int MAX_NUM_REPEATS = 3;
public static final int LAST_CELL = 11;
/**
* Constructor for objects of class WizardController.
*/
public WizardController(Wizard aWizard1, Wizard aWizard2)
{
super();
this.wizard1 = aWizard1;
this.wizard2 = aWizard2;
this.numOfRepeats = 0;
}
/* instance methods */
/**
* Prompts the user for a number of action repeats
* in the range 1 to 3 inclusive, and returns this number.
*/
public int promptForNumOfRepeats()
{
int moves;
moves = Integer.parseInt(OUDialog.request("Please enter the number of"
+ " action repeats to be performed - between 1 and 3 (inclusive)"));
try
{
moves = Integer.parseInt(OUDialog.request("Please enter the number of"
+ " action repeats to be performed - between 1 and 3 (inclusive)"));
}
catch (NumberFormatException anException)
{
moves = 0;
}
return moves;
}
/**
* Returns true if the argument is in the range 1 to 3 (inclusive),
* otherwise false.
*/
public boolean isValidNumOfRepeats(int aNumber)
{
return ((aNumber >= WizardController.MIN_NUM_REPEATS)
&& (aNumber <= WizardController.MAX_NUM_REPEATS));
}
/**
* Repeatedly prompts the user for a number of repeats of the moves,
* until they enter a valid input representing a number in the range 1 to 3
* inclusive, and then returns this number.
*/
public int getNumOfRepeats()
{
int repeats = this.promptForNumOfRepeats();
while (!this.isValidNumOfRepeats(repeats))
{
OUDialog.alert("That is not a valid number of game repeats");
repeats = this.promptForNumOfRepeats();
}
return repeats;
}
public static void jump(Wizard wizard1)
{
wizard1.up();
WizardController.delay(1000);
wizard1.down(1);
}
public static void delay(int ms)
{
try{
Thread.sleep(ms);
}
catch(Exception e)
{
System.out.println("Problem in delay methods");
}
}
}
here is the Wizard class for any wxtra help:
public class Wizard
{
/* instance variables */
private Triangle persona;
private int startCellX;
private int startCellY;
private OUColour startColour;
public static final int CELL_SIZE_X = 20;
public static final int CELL_SIZE_Y = 30;
/**
* Constructor for objects of class Wizard
*/
public Wizard(OUColour aColour, int cellY)
{
super();
this.persona = new Triangle(30, 30, aColour);
this.persona.setXPos(0);
this.persona.setYPos(cellY * Wizard.CELL_SIZE_Y);
this.startCellX = 0;
this.startCellY = cellY;
this.startColour = aColour;
}
/* instance methods */
/**
* returns the persona of the Wizard - so that it can be displayed
* in the graphical display window
*/
public Triangle getPersona()
{
return this.persona;
}
/**
* Resets the receiver to its "home" X position of 0.
*/
public void homeX()
{
this.persona.setXPos(this.startCellX * Wizard.CELL_SIZE_X);
}
/**
* Resets the receiver to its "home" Y position of startCellY * CELL_SIZE.
*/
public void homeY()
{
this.persona.setYPos(this.startCellY * Wizard.CELL_SIZE_Y);
}
/**
* Decrements the X position of the receiver by CELL_SIZE.
*/
public void left()
{
this.persona.setXPos(this.persona.getXPos() - Wizard.CELL_SIZE_X);
}
/**
* Increments the X position of the receiver by CELL_SIZE.
*/
public void right()
{
this.persona.setXPos(this.persona.getXPos() + Wizard.CELL_SIZE_X);
}
/**
* Decrements the Y position of the receiver by CELL_SIZE.
*/
public void up()
{
this.persona.setYPos(this.persona.getYPos() - Wizard.CELL_SIZE_Y);
}
/**
* Increments the Y position of the receiver by CELL_SIZE.
*/
public void down()
{
this.persona.setYPos(this.persona.getYPos() + Wizard.CELL_SIZE_Y);
}
/**
* Decrements the X position of the receiver by CELL_SIZE
* times the value of the argument.
*/
public void leftBy(int numCells)
{
this.persona.setXPos(this.persona.getXPos() - Wizard.CELL_SIZE_X * numCells);
}
/**
* Increments the X position of the receiver by CELL_SIZE
* times the value of the argument.
*/
public void rightBy(int numCells)
{
this.persona.setXPos(this.persona.getXPos() + Wizard.CELL_SIZE_X * numCells);
}
/**
* Decrements the Y position of the receiver by CELL_SIZE
* times the value of the argument.
*/
public void upBy(int numCells)
{
this.persona.setYPos(this.persona.getYPos() - Wizard.CELL_SIZE_Y * numCells);
}
/**
* Increments the Y position of the receiver by CELL_SIZE
* times the value of the argument.
*/
public void downBy(int numCells)
{
this.persona.setYPos(this.persona.getYPos() + Wizard.CELL_SIZE_Y * numCells);
}
/**
* returns the cellX the wizard is currently on
*/
public int getCellX()
{
return this.persona.getXPos()/ Wizard.CELL_SIZE_X;
}
/**
* returns the cellY the wizard is currently on
*/
public int getCellY()
{
return this.persona.getYPos()/ Wizard.CELL_SIZE_Y;
}
/**
* sets the cellY the wizard is on to the argument
*/
public void setCellY(int aCellNumber)
{
this.persona.setYPos(aCellNumber * Wizard.CELL_SIZE_Y);
}
/**
* Returns a string representation of the receiver.
*/
#Override
public String toString()
{
return "An instance of class " + this.getClass().getName()
+ " in cell X:" + this.getCellX() + ", Y:" + this.getCellY()
+ ", colour " + this.persona.getColour();
}

Override method error

I am getting the following error when I'm compiling my code...
BSLinkedList.java:10: error: BSLinkedList is not abstract and does not override abstract method push(T) in BoundedStack
public class BSLinkedList <T> implements BoundedStack<T>{
^
where T is a type-variable:
T extends Object declared in class BSLinkedList
I have tried to make sure that everything I am using is generic type T. All of the questions I've found on this topic say that people have not implemented a method from the interface, however I have implemented the method push as well as all other methods from my interface! I appreciate any help or guidance anyone can supply! Thank you!
import java.util.EmptyStackException;
import java.util.*;
/**
* The class BSLinkedList implements the Stack ADT as described
* in cpsc331Stack using a linked list
*
* #version 1.0
*/
public class BSLinkedList <T> implements BoundedStack<T>{
public class StackNode<T> {
private T value;
public StackNode<T> next;
private int capacity;
public StackNode<T> top;
private int size;
public StackNode(T x, StackNode<T> n){
value = x;
next = n;
}
public void BSLinkedList(int capacity) {
assert capacity >= 0;
LinkedList<T> stack = new LinkedList<T>();
size = 0;
top = (StackNode<T>)null;
}
public boolean isEmpty(){
assert size >= 0;
if (size == 0){
return true;
}
else{
return false;
}
}
public boolean isFull(){
if (size == capacity){
return true;
}
else{
return false;
}
}
public int capacity(){
return capacity;
}
public int size(){
return size;
}
public void push(T x) {
if (isFull()){
throw new FullStackException();
}
else{
++size;
top = new StackNode<T>(x, top);
}
}
public T top(){
if(isEmpty()){
throw new EmptyStackException();
}
else{
return top.value;
}
}
public T pop(){
if (isEmpty()){
throw new EmptyStackException();
}
else{
T e = top.value;
top = top.next;
--size;
return e;
}
}
}
}
and the interface...
/**
* The BoundedStack interface represents the Bounded Stack ADT as described in CPSC 331.
* This interface extends the interface cpsc331Stack.
*
* #version 1.0
*/
public interface BoundedStack<T> extends cpsc331Stack<T>{
/**
* Returns the number of elements currently on the stack.
*
* #return the number of elements on the stack
*/
public int size();
/**
* Returns the maximum number of elements the stack can store.
*
* #return the maximum number of elements the stack can store
*/
public int capacity();
/**
* Tests whether the stack is full.
*
* #return true if number of elements in the stack is equal to
* the stack's capacity, false otherwise
*/
public boolean isFull();
/**
* Pushes the object x onto the top of the stack.
*
* #param x object to be pushed onto the stack.
* #throws FullStackException if the stack is full
*/
public void push (T x);
}
Other implementation that is working correctly...
import java.util.EmptyStackException;
/**
* The class BSArray implements the Stack ADT as described
* in cpsc331Stack using an array
*
* #version 1.0
*/
public class BSArray <T> implements BoundedStack<T>{
private T[] stack;
private int size;
private int top = -1;;
private int capacity;
/**
* Creates a new BSArray of size capacity
*
* #param capacity integer value of the maximum number of elements the array can store
*/
public BSArray(int capacity) {
assert capacity >= 0;
stack = (T[]) new Object[capacity];
}
/**
* Tests whether or not the stack is empty.
*
* #return true if the stack is empty, false otherwise
*/
public boolean isEmpty(){
if (size >= 0){
return true;
}
else{
return false;
}
}
/**
* Tests whether or not the stack is full.
*
* #return true if number of elements in the stack is equal to
* the stack's capacity, false otherwise
*/
public boolean isFull(){
if (size == capacity){
return true;
}
else{
return false;
}
}
/**
* Returns the maximum number of elements the stack can store.
*
* #return the maximum number of elements the stack can store
*/
public int capacity(){
return capacity;
}
/**
* Returns the number of elements currently on the stack.
*
* #return the number of elements on the stack
*/
public int size(){
return size;
}
/**
* Pushes the object x onto the top of the stack.
*
* #param x object to be pushed onto the stack.
* #throws FullStackException if the stack is full
*/
public void push(T x){
if (isFull()){
throw new FullStackException();
}
else{
++top;
++size;
stack[top] = x;
}
}
/**
* Returns the object at the top of the stack.
*
* #return reference to the item at the top of the stack
* #throws EmptyStackException if the stack is empty
*/
public T top(){
if(isEmpty()){
throw new EmptyStackException();
}
else{
return (T) stack[top];
}
}
/**
* Removes and returns the object at the top of the stack.
*
* #return reference to the item at the top of the stack
* #throws EmptyStackException if the stack is empty
*/
public T pop(){
if (isEmpty()){
throw new EmptyStackException();
}
else{
assert top >= -1;
T e = stack[top];
stack[top] = null;
--top;
--size;
return e;
}
}
}
cpsc331Stack interface
/**
* The cpsc331Stack interface represents the Stack ADT as described
* in CPSC 331.
*
* #version 1.0
*/
public interface cpsc331Stack<T> {
/**
* Tests whether the stack is empty.
*
* #return true if the stack is empty, false otherwise
*/
public boolean isEmpty();
/**
* Pushes the object x onto the top of the stack.
*
* #param x object to be pushed onto the stack.
*/
public void push(T x);
/**
* Returns the object at the top of the stack.
*
* #return reference to the item at the top of the stack
* #throws EmptyStackException if the stack is empty
*/
public T top();
/**
* Removes and returns the object at the top of the stack.
*
* #return reference to the item at the top of the stack
* #throws EmptyStackException if the stack is empty
*/
public T pop();
}
This is a bit speculative, but I believe the problem you are seeing is because your push() method does not actually override the exact signature you specified in your interface. You have this:
public void push(T x) throws FullStackException { }
but the interface has this:
public void push (T x);
For a quick fix, you can update the interface to throw the FullStackException.
By the way, the error you are seeing is a standard Java 101 error which occurs when you extend an abstract class without overriding all the abstract methods contained within that class. So your compiler thinks that there is an abstract method push() out there which you never overrode (even though you did, at least functionally speaking).
You have implemented the methods in the StackNode inner class but it is the outer class BSLinkedList which implements the interface.
In addition, as mentioned in the previous answer the push method declares an exception that is not in the interface method signature. This will result in an different error when you fix other issue.
**Edit in your second example you are have correctly implemented the methods in the class that implements the interface (you do not have the inner class).
Is this what you are trying to achieve?
/**
* The class BSLinkedList implements the Stack ADT as described
* in cpsc331Stack using a linked list
*
* #version 1.0
*/
public class BSLinkedList<T> implements BoundedStack<T> {
private int capacity;
public StackNode<T> top;
private int size;
public void BSLinkedList(int capacity) {
assert capacity >= 0;
LinkedList<T> stack = new LinkedList<T>();
size = 0;
top = null;
}
public boolean isEmpty() {
assert size >= 0;
if (size == 0) {
return true;
} else {
return false;
}
}
public boolean isFull() {
if (size == capacity) {
return true;
} else {
return false;
}
}
public int capacity() {
return capacity;
}
public int size() {
return size;
}
#Override
public void push(T x) {
if (isFull()) {
throw new FullStackException();
} else {
++size;
top = new StackNode<T>(x, top);
}
}
public T top() {
if (isEmpty()) {
throw new EmptyStackException();
} else {
return top.value;
}
}
public T pop() {
if (isEmpty()) {
throw new EmptyStackException();
} else {
T e = top.value;
top = top.next;
--size;
return e;
}
}
public class StackNode<T> {
private T value;
public StackNode<T> next;
public StackNode(T x, StackNode<T> n) {
value = x;
next = n;
}
}
}
Your method signature should match exactly with the method it is overriding. So, either remove the throws Exception from push method of BSLinkedList class or add the throws exception in the push method of BoundedStack interface.
Moreover, your class overrides all the methods of the BoundedStack interface. However, there may be certain methods which are defined in cpsc331Stack which you have to implement in your class.
Kindly post the source code of cpsc331Stack interface here so that we can help you better
You have actually defined the methods size(),capacity(),isFull(),push() inside the innerclass "StackNode" which is defined inside "BSLinkedList".If that is what you were actually intending,then "StackNode" class should implement "BoundedStack" instead of "BSLinkedList" implementing "BoundStack",else the method should be defined inside "BSLinkedList".
`class BSLinkedList <T>{
public class StackNode<T> implements BoundedStack<T>{
private T value;
public StackNode<T> next;
private int capacity;
public StackNode<T> top;
private int size;
public StackNode(T x, StackNode<T> n){
value = x;
next = n;
}
public void BSLinkedList(int capacity) {
assert capacity >= 0;
LinkedList<T> stack = new LinkedList<T>();
size = 0;
top = (StackNode<T>)null;
}
public boolean isEmpty(){
assert size >= 0;
if (size == 0){
return true;
}
else{
return false;
}
}
#Override
public boolean isFull(){
if (size == capacity){
return true;
}
else{
return false;
}
}
#Override
public int capacity(){
return capacity;
}
#Override
public int size(){
return size;
}
#Override
public void push(T x) {
if (isFull()){
throw new FullStackException();
}
else{
++size;
top = new StackNode<T>(x, top);
}
}
public T top(){
if(isEmpty()){
throw new EmptyStackException();
}
else{
return top.value;
}
}
public T pop(){
if (isEmpty()){
throw new EmptyStackException();
}
else{
T e = top.value;
top = top.next;
--size;
return e;
}
}
}
}`

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.

Why PageableListView doesn't have constructor without model or list

In my application I need pageableListView combine with propertyListView. I just wonder why pageableListView doesnt have contructor without model or list. I just create new class which extend propertyListView and have body with pageableListView and one additional constructor just with string = id and number of rows. Now it looking good and also it work. Did I miss something that this shouldnt work sometimes ?
package org.toursys.web.components;
import java.util.List;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.list.PropertyListView;
import org.apache.wicket.model.IModel;
public abstract class PropertyPageableListView<T> extends PropertyListView<T> implements IPageableItems {
private static final long serialVersionUID = 1L;
/** The page to show. */
private int currentPage;
/** Number of rows per page of the list view. */
private int itemsPerPage;
/**
* Constructor
*
* #param id
* See Component
* #param model
* See Component
* #param itemsPerPage
* Number of rows to show on a page
*/
public PropertyPageableListView(final String id, int itemsPerPage) {
super(id);
this.itemsPerPage = itemsPerPage;
}
/**
* Constructor
*
* #param id
* See Component
* #param model
* See Component
* #param itemsPerPage
* Number of rows to show on a page
*/
public PropertyPageableListView(final String id, final IModel<? extends List<? extends T>> model, int itemsPerPage) {
super(id, model);
this.itemsPerPage = itemsPerPage;
}
/**
* Creates a pageable list view having the given number of rows per page that uses the provided object as a simple
* model.
*
* #param id
* See Component
* #param list
* See Component
* #param itemsPerPage
* Number of rows to show on a page
* #see ListView#ListView(String, List)
*/
public PropertyPageableListView(final String id, final List<? extends T> list, final int itemsPerPage) {
super(id, list);
this.itemsPerPage = itemsPerPage;
}
/**
* Gets the index of the current page being displayed by this list view.
*
* #return Returns the currentPage.
*/
public final int getCurrentPage() {
// If first cell is out of range, bring page back into range
while ((currentPage > 0) && ((currentPage * itemsPerPage) >= getItemCount())) {
currentPage--;
}
return currentPage;
}
/**
* Gets the number of pages in this list view.
*
* #return The number of pages in this list view
*/
public final int getPageCount() {
return ((getItemCount() + itemsPerPage) - 1) / itemsPerPage;
}
/**
* Gets the maximum number of rows on each page.
*
* #return the maximum number of rows on each page.
*/
public final int getItemsPerPage() {
return itemsPerPage;
}
/**
* Sets the maximum number of rows on each page.
*
* #param itemsPerPage
* the maximum number of rows on each page.
*/
public final void setItemsPerPage(int itemsPerPage) {
if (itemsPerPage < 0) {
itemsPerPage = 0;
}
addStateChange();
this.itemsPerPage = itemsPerPage;
}
/**
* #return offset of first item
*/
public int getFirstItemOffset() {
return getCurrentPage() * getItemsPerPage();
}
/**
* #see org.apache.wicket.markup.html.navigation.paging.IPageableItems#getItemCount()
*/
public int getItemCount() {
return getList().size();
}
/**
* #see org.apache.wicket.markup.html.list.ListView#getViewSize()
*/
#Override
public int getViewSize() {
if (getDefaultModelObject() != null) {
super.setStartIndex(getFirstItemOffset());
super.setViewSize(getItemsPerPage());
}
return super.getViewSize();
}
/**
* Sets the current page that this list view should show.
*
* #param currentPage
* The currentPage to set.
*/
public final void setCurrentPage(int currentPage) {
if (currentPage < 0) {
currentPage = 0;
}
int pageCount = getPageCount();
if ((currentPage > 0) && (currentPage >= pageCount)) {
currentPage = pageCount - 1;
}
addStateChange();
this.currentPage = currentPage;
}
/**
* Prevent users from accidentally using it.
*
* #see org.apache.wicket.markup.html.list.ListView#setStartIndex(int)
* #throws UnsupportedOperationException
* always
*/
#Override
public ListView<T> setStartIndex(int startIndex) throws UnsupportedOperationException {
throw new UnsupportedOperationException("You must not use setStartIndex() with PageableListView");
}
/**
* Prevent users from accidentally using it.
*
* #param size
* the view size
* #return This
* #throws UnsupportedOperationException
* always
* #see org.apache.wicket.markup.html.list.ListView#setStartIndex(int)
*/
#Override
public ListView<T> setViewSize(int size) throws UnsupportedOperationException {
throw new UnsupportedOperationException("You must not use setViewSize() with PageableListView");
}
}
It would be easier for you to extend PageableListView and just add one method to make it work like PropertyListView:
/**
* Wraps a ListItemModel in a CompoundPropertyModel.
*
* #param model
* #param index
* #return a CompoundPropertyModel wrapping a ListItemModel
*/
#Override
protected IModel<T> getListItemModel(final IModel<? extends List<T>> model, final int index)
{
return new CompoundPropertyModel<T>(super.getListItemModel(model, index));
}
You can file a RFE for the additional constructor too.

How do I call methods from a class with an arraylist to another class?

I'm in my first semester of Java and I need help in calling methods from the VotingMachine class below to the Candidate Class. The Voting Machine class is compiling properly. Thank you all for any help you can provide....
Mercedes
import java.util.ArrayList;
/**
* These are the fields for the Voting Machine Class.
*/
public class VotingMachine
{
private ArrayList<String> candidateList;
/**
* The following constructor will establish the Candidate List
*/
public VotingMachine()
{
candidateList = new ArrayList<String>();
}
/**
* This constructor will store the Candidates for the Candidate List
*/
public void setCandidateList()
{
candidateList.add("Darnell Woffard");
candidateList.add("Barack Obama");
candidateList.add("Hillary Clinton");
}
/**
* This method will display the entire Candidate List.
*/
public void printCandidateInfo()
{
for (int index=0; index < candidateList.size(); index++)
{
System.out.println(candidateList.get(index));
}
}
/**
* Method to the number of Candidates in the CandidateList Arraylist.
*/
public int getNumberofFiles()
{
return candidateList.size();
}
/**
* Method to select one candidate by first providing an index number.
*/
public void listFile(int index)
{
if(index >= 0 && index < candidateList.size()){
String filename = candidateList.get(index);
System.out.println(filename);
}
}
/**
* This method will enable a user to remove a candidate.
*/
public void removeFile(int index)
{
if(index >= 0 && index < candidateList.size()){
candidateList.remove(index);
}
}
/**
* This method will add a file to the Candidate List.
*
*/
public void addCandidate(String filename)
{
candidateList.add(filename);
}
//----------
//The Candidate Class:
public class Candidate{
private String name;
private char party;
private String candidateList;
// Add fields
/**
* Fields
* name - Candidate's name, stored in a String
* party - Candidate's political party, stored in a char
* as 'r' for Republican, 'd' for Democrat, and 'i' for Independent
*/
/**
* Constructor
*
* #param anyName - caller inputs Candidate name
* #param anyParty - caller inputs Candidate's party affiliation
* stored as a char
* chars are assigned with single quotes.
*/
public Candidate(String anyName, char anyParty)
{
name = anyName;
party = anyParty;
}
/**
* The method will enable method calls from the Voting Machine Class.
*/
public void main(String candidateList)
{
VotingMachine votingMachine = new VotingMachine();
}
/**
* This method will define the candidates party affiliation.
* public char setParty()
*/
//Complete the three methods and their comments.
/**
* Method to retrieve the Candidate's name for the caller.
* public String getName(String anyName)
*
*/
/**
* Method to retrieve the Candidate's party for the caller.
*
* #return
*/
/**
* Method to change the Candidate's party
*
* #param
*/
Actually what i got from this is you are trying to make a voting machine. VotingMachine is the main class here having info of different candidates. so we will make object of candidate in votingMachine class. Note: when we are supposed to make a java project, figure out what is it main class and subclass that means which depends on which. in the above example There is association in the classes. First of all declare an ArrayList for storing objects of candidate class. as shown below.
private ArrayList<candidate> candidateList;
/**
* The following constructor will establish the Candidate List
*/
public VotingMachine()
{
candidateList = new ArrayList<String>();
}
now for adding new candidate in the ArrayList I have modified your method
setCandidate()
as
public void addNewCandidate(String name, char partySymbol)
{
candidate candid = new candidate(name, partySymbol);// this will call the candidate constructor
candidateList.add(candid);//add that object in ArrayList
}
As ArrayList stores references of objects, the built-in function int get(int index) will return the reference of the object. to print the info of that object or you can say values, we should define a function as getName() and getParty(). instead of this System.out.println(candidateList.get(index)); you should call System.out.println(candidateList.get(index).getName()); and System.out.println(candidateList.get(index).getParty());in the following method
public void printCandidateInfo()
{
for (int index=0; index < candidateList.size(); index++)
{
System.out.println(candidateList.get(index));
}
}
so define functions in candidate class as
public String getName()
{
return name;
}
/**
* Method to retrieve the Candidate's party for the caller.
*
* #return
*/
public char getParty()
{
return party;
}
the following method will print the reference not the info of candidate, so modify it as described above
public void listFile(int index)
{
if(index >= 0 && index < candidateList.size()){
String filename = candidateList.get(index);
System.out.println(filename);
}
}
as i have modified it,
import java.util.ArrayList;
/**
* These are the fields for the Voting Machine Class.
*/
public class VotingMachine
{
private ArrayList<Candidate> candidateList;
/**
* The following constructor will establish the Candidate List
*/
public VotingMachine()
{
candidateList = new ArrayList<>();
}
/**
* This method will store the Candidates for the Candidate List
*/
public void addNewCandidate(String name, char partySymbol)
{
Candidate candid = new Candidate(name, partySymbol);// this will call the candidate constructor
candidateList.add(candid);//add that object in ArrayList
}
/**
* This method will display the entire Candidate List.
*/
public void printCandidateInfo()
{
for (int index=0; index < candidateList.size(); index++)
{
System.out.print(candidateList.get(index).getName());
System.out.println(" " + candidateList.get(index).getParty());
}
}
/**
* Method to the number of Candidates in the CandidateList Arraylist.
*/
public int getNumberofFiles()
{
return candidateList.size();
}
/**
* Method to select one candidate by first providing an index number.
*/
public void listFile(int index)
{
System.out.print(candidateList.get(index).getName());
System.out.println(" " + candidateList.get(index).getParty());
}
/**
* This method will enable a user to remove a candidate.
*/
public void removeFile(int index)
{
if(index >= 0 && index < candidateList.size()){
candidateList.remove(index);
}
}
}
in candidate class i have just added the above mentioned getName() and getParty() methods..
regards

Categories