Im trying to run BFS Algo and it throws me out - java

I`m trying to run BFS, when i get to PriorityQueue openList.add(state)
the first time it works and the secound time it dosent.
The error is:
Exception in thread "main" java.lang.ClassCastException: algorithms.mazeGenerators.Position cannot be cast to java.lang.Comparable
at java.util.PriorityQueue.siftUpComparable(Unknown Source)
at java.util.PriorityQueue.siftUp(Unknown Source)
at java.util.PriorityQueue.offer(Unknown Source)
at java.util.PriorityQueue.add(Unknown Source)
at algorithms.searchers.BFS.search(BFS.java:30)
at boot.Run.main(Run.java:18)
BFS CLASS:
public class BFS extends CommonSearcher {
#Override
public Solution search(Searchable s) {
State cur = null;
s.getStartState().setCost(0);
openList.add(s.getStartState());
HashSet<State> closedSet = new HashSet<State>();
while (!openList.isEmpty()) {
cur = popOpenList();
closedSet.add(cur);
if (cur.equals(s.getGoalState())) {
return backTrace(cur, s.getStartState());
}
ArrayList<State> successors = s.getAllPossibleStates(cur);
for (State state : successors) {
if (!closedSet.contains(state) && !openList.contains(state)) {
state.setCameFrom(cur);
state.setCost(cur.getCost() + 1);
openList.add(state);
} else {
if (openList.contains(state)) {
if (state.getCost() < returnWantedState(state).getCost()) {
openList.remove(state);
openList.add(state);
adjustPriorityList();
}
} else {
openList.add(state);
adjustPriorityList();
}
}
}
}
return null;
}
/*
* public State popOpenList() { State temp = openList.remove(); for (State
* state : openList) { if (temp.getCost() > state.getCost()) {
* openList.add(temp); temp = state; openList.remove(state); } } return
* temp;
*
* }
*/
public void adjustPriorityList() {
State temp = openList.remove();
for (State state : openList) {
if (temp.getCost() < state.getCost()) {
openList.add(temp);
temp = state;
openList.remove(state);
}
}
openList.add(temp);
}
public State returnWantedState(State state) {
for (State state1 : openList) {
if (state.equals(state1))
state = state1;
}
return state;
}
}
CommonSearcher Class:
package algorithms.searchers;
import java.util.PriorityQueue;
import algorithms.mazeGenerators.Searchable;
import algorithms.mazeGenerators.Solution;
import algorithms.mazeGenerators.State;
public abstract class CommonSearcher implements Searcher {
protected PriorityQueue<State> openList;
private int evaluatedNodes;
public CommonSearcher() {
openList = new PriorityQueue<State>();
evaluatedNodes = 0;
}
protected State popOpenList(){
evaluatedNodes++;
return openList.poll();
}
#Override
public abstract Solution search(Searchable s);
#Override
public int getNumberOfnodesEvaluated() {
// TODO Auto-generated method stub
return evaluatedNodes;
}
protected Solution backTrace(State goalState, State startState){
Solution sol = new Solution();
while(!goalState.equals(startState)){
sol.getSolutionList().add(goalState.getState());
goalState = goalState.getCameFrom();
}
return sol;
}
}
State Class:
package algorithms.mazeGenerators;
public abstract class State {
protected String state; // the state represented by a string
protected double cost; // cost to reach this state
protected State cameFrom; // the state we came from to this state
public State(){
}
public State(String state){ // CTOR
this.state = state;
}
#Override
public boolean equals(Object obj){ // we override Object's equals method
return state.equals(((State)obj).state);
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public double getCost() {
return cost;
}
public void setCost(double cost) {
this.cost = cost;
}
public State getCameFrom() {
return cameFrom;
}
public void setCameFrom(State cameFrom) {
this.cameFrom = cameFrom;
}
}
Position Class:
package algorithms.mazeGenerators;
import java.util.ArrayList;
public class Position extends State {
// Data members
private int x, y, z;
private int wallOrNot;
private boolean visted;
// Constructor
public Position() {
visted = false;
wallOrNot = 1;
}
/*
* The method gets the position details
* and checks if its a wall or not
* if its a wall then its marked as visited.
* */
public void setPos(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
if (z % 2 != 0 || x % 2 != 0 || y % 2 != 0)
visted = true;
setState("{" + x+"," + y+","+ z +"}");
}
// getrs and setters
public int getWallOrNot() {
return wallOrNot;
}
public void setWallOrNot(int wallOrNot) {
this.wallOrNot = wallOrNot;
}
public boolean isVisted() {
return visted;
}
public void setVisted(boolean visted) {
this.visted = visted;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getZ() {
return z;
}
public void setZ(int z) {
this.z = z;
}
/*
* This method gets returns all a list of neighbors that hasn't marked as visited for a specific Position.
* returns the list of neighbors.
* */
public ArrayList<Position> getNeighbors(Position[][][] maze) {
ArrayList<Position> neighbors = new ArrayList<Position>();
if (this.x > 1)
if (maze[x - 2][y][z].isVisted() == false)
neighbors.add(maze[x - 2][y][z]);
if (this.x < maze.length - 2)
if (maze[x + 2][y][z].isVisted() == false)
neighbors.add(maze[x + 2][y][z]);
if (this.y > 1)
if (maze[x][y - 2][z].isVisted() == false)
neighbors.add(maze[x][y - 2][z]);
if (this.y < maze[x].length - 2)
if (maze[x][y + 2][z].isVisted() == false)
neighbors.add(maze[x][y + 2][z]);
if (this.z > 1)
if (maze[x][y][z - 2].isVisted() == false)
neighbors.add(maze[x][y][z - 2]);
if (this.z < maze[x][y].length - 2)
if (maze[x][y][z + 2].isVisted() == false)
neighbors.add(maze[x][y][z + 2]);
return neighbors;
}
public String toString(){
return "{" + x+"," + y+","+ z +"}";
}
public boolean equals(Object obj){ // we override Object's equals method
return state.equals(((Position)obj).state);
}
}

The purpose of a priority queue requires an ordering of its elements.
In Java's PriorityQueue this can be done by either making the elements implement the Comparable interface,
or by specifying a Comparator.
I`m trying to run BFS, when i get to PriorityQueue openList.add(state) the first time it works and the secound time it dosent.
If you insert only one object into a PriorityQueue,
it will work even if the object doesn't implement the Comparable interface,
because a single object doesn't need to be compared to anything.
You get a ClassCastException when you insert a second object,
if the objects don't implement Comparable and you didn't provide a Comparator.
public abstract class State implements Comparable<State> {
// ...
#Override
public int compareTo(State other) {
if (getCost() > other.getCost()) {
return -1;
}
if (getCost() < other.getCost()) {
return 1;
}
return 0;
}
}

PriorityQueue requires its element to implement the Comparable interface, yet your State class does not do it.
From the java docs:
A priority queue relying on natural ordering also does not permit
insertion of non-comparable objects (doing so may result in
ClassCastException).
You need to make your State class something like:
public abstract class State implements Comparable<State> {
....
#Override
public int compareTo(State s) {
...
}
}

Related

How to merge two alike items within the ArrayList?

So, I have 1 superclass DessertItem. Which has 4 subclasses Candy, Cookie, Ice Cream, Sundae. The Sundae class extends the Ice Cream class. Superclass is an abstract class. I also have a separate class which does not belong to the superclass, but in the same package - Order. There is another class - DessertShop, where the main is located.
Candy, Cookie classes implement SameItem<> generic class. The generic interface SameItem<> class looks like this:
public interface SameItem<T> {
public boolean isSameAs(T other);
}
The Candy, Cookie classes have this method:
#Override
public boolean isSameAs(Candy other) {
if(this.getName() == other.getName() && this.getPricePerPound() == other.getPricePerPound()) {
return true;
}
else {
return false;
}
}
And something similar, but for the cookie class.
All the subclasses have these methods :
default constructor,
public Cookie(String n, int q, double p) {
super(n);
super.setPackaging("Box");
cookieQty = q;
pricePerDozen = p;
}
public int getCookieQty() {
return cookieQty;
}
public double getPricePerDozen() {
return pricePerDozen;
}
public void setCookieQty(int q) {
cookieQty = q;
}
public void setToppingPricePricePerDozen(double p) {
pricePerDozen = p;
}
#Override
public double calculateCost() {
double cookieCost = cookieQty * (pricePerDozen/12);
return cookieCost;
}
and toString() method
So, what my program does is gets the input from the User, asks the name of the dessert, asks the quantity, or the quantity according to the dessert, ask the unit price. Asks the payment method. And then prints the receipt. This how the Order class looks like:
import java.util.ArrayList;
import java.util.List;
public class Order extends implements Payable{
//attributes
PayType payMethod;
private ArrayList<DessertItem> OrderArray;
//Constructor
public Order() {
OrderArray = new ArrayList<>();
payMethod = PayType.CASH;
}
//methods
public ArrayList<DessertItem> getOrderList(){
return OrderArray;
}// end of getOrderList
public ArrayList<DessertItem> Add(DessertItem addDesert){
enter code here
OrderArray.add(addDesert);
/* for(DessertItem i : getOrderList()) {
if(i instanceof Candy) {
for(DessertItem j : getOrderList()) {
if(j instanceof Candy) {
if(((Candy) i).isSameAs((Candy) j)) {
*/
//this is what I have tried so far, but I am lost
}
}
}
} else if(i instanceof Cookie) {
for (DessertItem j : getOrderList()) {
if(((Cookie) i).isSameAs((Cookie)j)) {
OrderArray.add(j);
} else {
OrderArray.add(i);
}
}
}
}
return OrderArray;
}// end of Add
public int itemCount(){
int counted = OrderArray.size();
return counted;
}//end of itemCount
public double orderCost() {
double orderResult = 0;
for(int i=0; i<OrderArray.size(); i++) {
orderResult = orderResult + OrderArray.get(i).calculateCost();
}
return orderResult;
}
public double orderTax() {
double taxResult = 0;
for(int i = 0; i<OrderArray.size(); i++) {
taxResult = taxResult + OrderArray.get(i).calculateTax();
}
return taxResult;
}
public double orderTotal() {
double ordertotal = orderTax() + orderCost();
return ordertotal;
}
#Override
public PayType getType() {
// TODO Auto-generated method stub
return payMethod;
}
#Override
public void setPayType(PayType p) {
payMethod = p;
}
public String toString() {
String finalOutput = "";
finalOutput += "------------------------Receipt--------------------------\n";
for(int i = 0; i < OrderArray.size(); i++) {
finalOutput = finalOutput + OrderArray.get(i).toString();
}
finalOutput += "--------------------------------------------------\n";
String line2 = "Total Number of items in order: " + itemCount() + "\n";
String line3 = String.format("Order Subtotals:\t\t\t\t $%-6.2f", orderCost());
String line4 = String.format("[Tax: $%.2f]\n", orderTax());
String line5 = String.format("\nOrder Total:\t\t\t\t\t $%-6.2f\n", orderTotal());
String outputVar = String.format("%s\n%s%s%17s", line2, line3, line4, line5);
String ending = "----------------------------------------------------";
String payType = String.format("\nPaid for with: %s", payMethod.name());
return finalOutput + outputVar + ending + payType;
}
So, my question is, how can I combine like items into one item?

How to Implement modifiable activation function in the neuron class in java?

I'm learning the concept of neural networks. I decided to try making the neuron class by myself. What is the best way to implement different activation functions in my code? Now it uses only the binary step function.
It's my first try in coding neural networks so if you have any suggestions about my code, or it is completely dumb, please let me know.
Here is my code:
public class Neuron {
// properties
private ArrayList<Neuron> input;
private ArrayList<Float> weight;
private float pot, bias, sense, out;
private boolean checked;
// methods
public float fire(){
pot = 0f;
if (input != null) {
for (Neuron n : input){
if (!n.getChecked()){
pot += n.fire()*weight.get(input.indexOf(n));
} else {
pot += n.getOut()*weight.get(input.indexOf(n));
} // end of condition (checked)
} // end of loop (for input)
} // end of condition (input exists)
checked = true;
pot -= bias;
pot += sense;
out = actFunc(pot);
return out;
} // end of fire()
// getting properties
public float getPot(){return pot;}
public boolean getChecked(){return checked;}
public float getOut(){return out;}
// setting properties
public void stimulate(float f){sense = f;}
public void setBias(float b){bias = b;}
public void setChecked(boolean c){checked = c;}
public void setOut(float o){out = o;}
// connection
public void connect(Neuron n, float w){
input.add(n);
weight.add(w);
}
public void deconnect(Neuron n){
weight.remove(input.indexOf(n));
input.remove(n);
}
// activation function
private float actFunc(float x){
if (x < 0) {
return 0f;
} else {
return 1f;
}
}
// constructor
public Neuron(Neuron[] ns, float[] ws, float b, float o){
if (ns != null){
input = new ArrayList<Neuron>();
weight = new ArrayList<Float>();
for (Neuron n : ns) input.add(n);
for (int i = 0; i < ws.length; i++) weight.add(ws[i]);
} else {
input = null;
weight = null;
}
bias = b;
out = o;
}
public Neuron(Neuron[] ns){
if (ns != null){
input = new ArrayList<Neuron>();
weight = new ArrayList<Float>();
for (Neuron n : ns) input.add(n);
for (int i = 0; i < input.size(); i++) weight.add((float)Math.random()*2f-1f);
} else {
input = null;
weight = null;
}
bias = (float)Math.random();
out = (float)Math.random();
}
}
First, define interface of any activation function:
public interface ActivationFunction {
float get(float f);
}
Then write some implementations:
public class StepFunction implements ActivationFunction {
#Override
public float get() {return (x < 0) ? 0f : 1f;}
}
public class SigmoidFunction implements ActivationFunction {
#Override
public float get() {return StrictMath.tanh(h);}
}
Finally, set some implementation to your Neuron:
public class Neuron {
private final ActivationFunction actFunc;
// other fields...
public Neuron(ActivationFunction actFunc) {
this.actFunc = actFunc;
}
public float fire(){
// ...
out = actFunc.get(pot);
return out;
}
}
as following:
Neuron n = new Neuron(new SigmoidFunction());
Note, neural netoworks are using signal propagation through neurons, where weights are produced. Computing of weight depends also on first derivative of an activation function. Therefore, I would extend ActivationFunction by method, which will return first derivative at specified point x:
public interface ActivationFunction {
float get(float f);
float firstDerivative(float x);
}
So the implemenations will look like:
public class StepFunction implements ActivationFunction {
#Override
public float get(float x) {return (x < 0) ? 0f : 1f;}
#Override
public float firstDerivative(float x) {return 1;}
}
public class SigmoidFunction implements ActivationFunction {
#Override
public float get(float x) {return StrictMath.tanh(x);}
// derivative_of tanh(x) = (4*e^(2x))/(e^(2x) + 1)^2 == 1-tanh(x)^2
#Override
public float firstDerivative(float x) {return 1 - Math.pow(StrictMath.tanh(x), 2);}
}
Then, use actFunction.firstDerivative(x); in fire() method where weight is being computed.

Trouble casting an interface to an implemented class

Here is my class:
public class LinkedListSet implements Set {
private class Node //much easier as a private class; don't have to extend
{
private int data;
private Node next;
public Node (){}
public Node (int x)
{
data = x;
}
public int data()
{
return data;
}
public Node next()
{
return next;
}
}
private Node first;
private int Size;
private int whichList; //used to identify the particular LL object
Here is my interface:
public interface Set {
public boolean isEmpty();
public void makeEmpty();
public boolean isMember(int x);
public void add(int x);
public void remove(int y);
public void union(Set other, Set result);
public void intersection (Set other, Set result);
public void difference (Set other, Set result);
#Override
public String toString();
#Override
public boolean equals(Object other);
public void setList(int i); //i added this to use it as an identifier for each
//list element in the set array
public String getListId(); //these two extra methods make life easier
}
I have a method like this (in the LinkedListSet class):
public void difference (Set other, Set result)
{
if (other.isEmpty())
{
System.out.println("The set is empty before cast");
}
LinkedListSet othr = (LinkedListSet) other;
LinkedListSet res = (LinkedListSet) result;
if (this.isEmpty() || othr.isEmpty())
{
if (othr.isEmpty())
System.out.println("The set is empty after cast");
if (this.isEmpty())
System.out.println("This is also empty");
return;
}
differenceHelper(this.first, othr.first, res);
result = res;
}// the print statements were added for debugging
The problem is, in the above method I am unable to cast the Set Other into its linked list implementation. When I call this method in the main program, the parameter is actually of type linked list (so I don't get any errors obviously).
However, all the instance variables are null. The list is empty before and after I cast it (when it actually isn't empty). I know this is because the interface doesn't include any information about the Nodes, but is there anything I can do other than editing the interface to incorporate the Node?
I hope I've made this clear enough. Any help would be appreciated.
edit:
In the main program I created an array of Sets.
Set[] sets = new Set[7];
for (int i = 0; i< sets.length; i++) //initialize each element
{
sets[i] = new LinkedListSet();
}
each list has nodes with data values which are added on later on in the code...
then I call the difference method.
sets[0].difference(sets[1], sets[4])
sets[1].isEmpty returns true for some reason (even though it is not).
If I were to do something like:
System.out.println(sets[1].first.data()) I would have no problem whatsoever.
For some reason all the values become null when the parameters are passed to the difference method.
public boolean isEmpty()
{
return first == null;
}
I tested what you are trying to do with the following code and I see no problems:
import org.junit.Test;
public class RandomCastTest {
public interface Set {
boolean isEmpty();
void add(int x);
void difference(Set other, Set result);
#Override
String toString();
#Override
boolean equals(Object other);
}
public class LinkedListSet implements Set {
private class Node //much easier as a private class; don't have to extend
{
private int data;
private Node next;
public Node() {
}
public Node(int x) {
data = x;
}
public int data() {
return data;
}
public Node next() {
return next;
}
public void next(Node node) {
next = node;
}
}
private Node first;
private int Size;
private int whichList; //used to identify the particular LL object
#Override
public boolean isEmpty() {
return first == null;
}
#Override
public void add(int x) {
Node node = new Node(x);
if (first == null) {
first = node;
} else {
Node currentNode;
Node nextNode = first;
do {
currentNode = nextNode;
nextNode = currentNode.next();
} while (nextNode != null);
currentNode.next(node);
}
Size++;
}
#Override
public void difference(Set other, Set result) {
if (other.isEmpty()) {
System.out.println("The set is empty before cast");
}
LinkedListSet othr = (LinkedListSet) other;
LinkedListSet res = (LinkedListSet) result;
if (this.isEmpty() || othr.isEmpty()) {
if (othr.isEmpty())
System.out.println("The set is empty after cast");
if (this.isEmpty())
System.out.println("This is also empty");
return;
}
result = res;
}
}
#Test
public void test() {
Set[] sets = new Set[7];
for (int i = 0; i < sets.length; i++) {
sets[i] = new LinkedListSet();
}
for (int i = 0; i < 5; i++) {
sets[1].add(i);
}
for (int i = 5; i < 10; i++) {
sets[0].add(i);
}
sets[0].difference(sets[1], sets[4]);
// ... find difference
}
}
To simplify I removed unimplemented methods from the interface. Also added the add method implementation. Please see if it works for you.

Sorting Custom class in java using Comparable

I've got this custom class and I want to sort it by saturation and brightness.
I've tried a custom comperator class, but it doesn't work.
Now I've tried to implement Comparable. The program runs through the code but doesn't sort the list at the end.
Here is my code.
Part of the testing class:
ArrayList<HSBColor> colorList = new ArrayList<HSBColor>(colors.values());
Collections.sort(colorList);
for(HSBColor co : colorList){
System.out.println(co.toString());
}
Custom Class HSBColor
public class HSBColor implements Comparable<HSBColor>{
private float H;
private float S;
private float B;
public HSBColor(float h, float s, float b) {
H = h;
S = s;
B = b;
}
public float getH() {
return H;
}
#Override
public String toString() {
return String.format("%.2f %.2f %.2f", H,S,B);
}
public void setH(float h) {
H = h;
}
public float getS() {
return S;
}
public void setS(float s) {
S = s;
}
public float getB() {
return B;
}
public void setB(float b) {
B = b;
}
#Override
public int compareTo(HSBColor o) {
if(this.getS() > o.getS() && this.getB() > o.getB()){
return 1;
}
else{
return -1;
}
}
}
Thanks in advance!
EDIT: Extra code
This are the colors before the sort:
Color HSB H:28.60465 S:71.07438 B:47.45098
Color HSB H:4.4999995 S:73.059364 B:85.882355 >> This is the one i need
Color HSB H:64.18605 S:79.62963 B:21.176472
Color HSB H:65.714294 S:39.873417 B:61.960785
Color HSB H:23.333332 S:40.0 B:70.588234
This are the colors after the sort
28,60 71,07 47,45
65,71 39,87 61,96
23,33 40,00 70,59
4,50 73,06 85,88
64,19 79,63 21,18
**EDIT new Algorithm **
This one compares it right, but doesn't sort them right..
#Override
public int compareTo(HSBColor o) {
if(this.getS() > o.getS()) {
if(this.getB() >o.getB()){
return 1;
}
else{
return 0;
}
}
else{
if(this.getB() < o.getB()){
return -1;
}
else{
return 0;
}
}
}
Your compareTo method doesn't define a proper ordering.
Suppose that this.getS() > o.getS() but this.getB() < o.getB().
this.compareTo(o) would return -1, but o.compareTo(this) would also return -1.
If A < B and B < A this is not a proper ordering.
A proper ordering would first compare by the more important property, and then, in case of equality, by the less important property.
For example :
#Override
public int compareTo(HSBColor o) {
if(this.getS() > o.getS()){
return 1;
} else if (this.getS() < o.getS()) {
return -1;
} else {
if (this.getB() > o.getB()) {
return 1;
} else if (this.getB() < o.getB()) {
return -1;
} else {
return 0;
}
}
}
There is an issue around compareTo method. You should use it like:
#Override
public int compareTo(HSBColor o) {//if saturation is equal then compare brightness.
if (this.S == o.getS()) {
return Float.compare(B, o.getB());
}
return Float.compare(S, o.getS());
}

Need mutator methods how do I do them

I am doing a UML and I am not quite sure how to do these mutator methods I am supposed to do this:
+turnOn(): void //sets on to true
+turnOff(): void //sets on to false
+channelUp(): void //increases channel by 1 if on, rolls to 1 after maximum
+channelDown(): void //decreases channel by 1 if on, rolls to maximum after 1
+volumeUp(): void //increases the volume by 1 if on and less than maximum
+volumeDown(): void //decreases volume by 1 if on and greater than 0
+toString( ): String //returns the current state(instance variable values)
my code right now: (keep in mind the mutator part isn't right)
public class TV {
private int volume;
private int channel;
private boolean on;
private int maxVolume;
private int maxChannel;
TV() {
volume = 1;
channel = 1;
on = false;
maxVolume = 1;
maxChannel = 1;
}
public int getChannel() {
return channel;
}
public int getVolume() {
return volume;
}
public boolean isOn() {
return on;
}
public int getMaxChannel() {
return maxChannel;
}
public int getMaxVolume() {
return maxVolume;
}
public void setChannel(int i) {
if (isOn() && i >= 1 && i <= maxChannel) channel = i;
}
public void setVolume(int i) {
if (isOn() && i >= 0 && i <= maxVolume) volume = i;
}
public void setMaxChannel(int i) {
maxChannel = i;
}
public void setMaxVolume(int i) {
maxVolume = i;
}
// + turnOn() * * This is where the mutator methods begin I need help here * *
// if (channel == maxChannel) channel = 1;
// else channel++;
//if (channel == 1) channel = max;
//else channel--;
// if (volume == maxVolume) volume = 1;
// else channel++;
//if (volume == 1) volume = max;
// else channel--;
public string toString() {
return "channel: " + channel + "\nvolume: " + volume +
"\non: " + on + "\nmax Channel: " + maxChannel +
"\nmax Volume: " + maxVolume;
}
}
Mutator generally means the same things as 'setter'
So in your above code, a 'getter' would be:
public int getMaxChannel() {
return maxChannel;
}
and a 'mutator' or 'setter' would be:
public void setMaxChannel(int maxChannel) {
this.maxChannel = maxChannel;
}
Sample methods:
public void turnOn() {
this.on = true;
}
public void channelUp() {
if (on) {
if (channel == maxChannel) {
channel = 1;
}
else {
channel++;
}
}
}
public void volumeDown() {
if (on && volume > 0) {
volume--;
}
}
Other methods follows the same logic.
Strings in java are objects, so your toString method signature should read public String toString().
We use setters and mutator as interchangeably.
A mutator method is used to set a value of a private field. It follows
a naming scheme prefixing the word "set" to the start of the method
name. These methods do not have a return type and accept a parameter
that is the same data type as their corresponding private field. The
parameter is then used to set the value of that private field.
Below are some examples of mutators or setters:
public void setMaxChannel(int i) {
maxChannel = i;
}
public void setChannel(int c) {
channel=c;
}

Categories

Resources