I have a class Vertex which implements Comparable and overrides equals.
public class Vertex implements Comparable<Vertex>{
private final int x;
private final int y;
private final char c;
public Vertex(int x, int y, char c) {
this.x = x;
this.y = y;
this.c=c;
}
public double heuristic(Vertex goal){
double dx = Math.abs(x - goal.x);
double dy = Math.abs(y - goal.y);
return Math.sqrt(Math.pow(dx, 2)+Math.pow(dy, 2));
}
#Override
public String toString() {
return ("(" + x + "," + y + ")"+"["+c+"]");
}
#Override
public int compareTo(Vertex v) {
// TODO Auto-generated method stub
if(this.heuristic(end)<v.heuristic(end)) return -1;
return 1;
}
public boolean equals(Vertex v){
if(this.x==v.x && this.y==v.y) return true;
return false;
}
/*
public boolean equals(Object o){
if(o.getClass().getName()=="Vretex"){
Vertex v=(Vertex)o;
return this.equals(v);
}
return false;
}
*/
}
When I use PriorityQueue and check if one object (different objects) that equal functionality according the equal function is in the PriorityQueue I get false.
Also tried the one in comment without success.
Your equals is wrong, it should be
#Override public boolean equals (Object other)...
i.e. the parameter must be an Object. Also you should implement hashCode too. See http://java67.blogspot.com.br/2013/04/example-of-overriding-equals-hashcode-compareTo-java-method.html for more information.
Related
I'm running into issues with Java Spark Dataset's groupByKey method. The following code, when run locally in a test environment (Spark 2.1.0, spark-core_2.11, spark-sql_2.11), throws the following exception:
java.lang.Exception: failed to compile: org.codehaus.commons.compiler.CompileException: File 'generated.java', Line 43, Column 21: No applicable constructor/method found for zero actual parameters; candidates are: "public int org.package.example.ExampleTest$1ExampleClass.getX()
Code is:
class ExampleClass implements Serializable {
private int x;
private int y;
public ExampleClass() {}
public ExampleClass(int x, int y) {this.x = x; this.y = y;}
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;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ExampleClass that = (ExampleClass) o;
if (x != that.x) return false;
return y == that.y;
}
#Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
}
ExampleClass exampleClass1 = new ExampleClass(1, 1);
ExampleClass exampleClass2 = new ExampleClass(1, 2);
ExampleClass exampleClass3 = new ExampleClass(1, 3);
List<ExampleClass> exampleClasses = Lists.newArrayList(
exampleClass1,
exampleClass2,
exampleClass3
);
Dataset<ExampleClass> dataset = spark.createDataset(exampleClasses, Encoders.bean(ExampleClass.class));
KeyValueGroupedDataset<Integer, ExampleClass> grouped = dataset.groupByKey(
(MapFunction<ExampleClass, Integer>) ExampleClass::getX,
Encoders.INT()
);
}
It looks like it can't find the default parameter-less constructor, or I'm leaving something out. Also interesting, if I change the ints to boxed Integers, it says the candidate is getY() not getX().
Any help is much appreciated!
EDIT: After messing around with it some more, moving ExampleClass out of a nested class in my test and into its own file fixes the problem. I still don't know why though so any answers are still appreciated.
I had the same issue. The problem in my case and I suspect in yours, is that your class isn't declared with the public modifier.
public class ExampleClass implements Serializable
Kudos to Andy Grove: https://www.mail-archive.com/user#spark.apache.org/msg55084.html
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) {
...
}
}
I have this sparse matrix implementation:
I'm trying to write getter/setter methods for individual elements based on their key, but I'm not sure how to do this with my custom type Coordinates. For example, theMatrix.get(coordinates) (the usual way) doesn't work.
Could someone show me how to do this?
Class coordinate is not accessible outside of your Matrix class.
Indeed, its an implementation detail that you don't want to make visible to the end-user. Please check the getters and setters in the example below.
If you still want to make Coordinates class available to the end-user, you wan make it public.
public class Matrix
{
private static class Coordinates
{
private int x = 0;
private int y = 0;
private int data = 0;
public Coordinates(final int x, final int y)
{
this.x = x;
this.y = y;
data = ((x + "") + (y + "")).hashCode();
}
#Override
public boolean equals(final Object obj)
{
if (obj instanceof Coordinates)
{
Coordinates Coordinates = (Coordinates) obj;
return ((x == Coordinates.x) && (y == Coordinates.y));
}
else
{
return false;
}
}
#Override
public int hashCode()
{
return data;
}
}
private int numrows;
private int numcolumns;
private HashMap<Coordinates, Double> theMatrix;
public Matrix(final int numrows, final int numcolumns)
{
this.numrows = numrows;
this.numcolumns = numcolumns;
}
public Matrix(HashMap<Coordinates, Double> matrixdata)
{
theMatrix = new HashMap<Coordinates, Double>(matrixdata);
}
public Double get(int row, int col, double defaultValue)
{
Double ret = theMatrix.get(new Coordinates(row, col));
return ret != null ? ret : defaultValue;
}
public void set(int row, int col, Double value)
{
theMatrix.put(new Coordinates(row, col), value);
}
}
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());
}
I am wondering why i have to deal with two types of arguments;that of a constructor and that of a method.For instance i have this simple class that adds two numbers
class Calc{
private int x = 6;
private int y;
private char z = 'z';
public int getx(){
return x;
}
public char selfrecur(){
return this.z;
}
public int add(int one,int two){
return one + two;
}
public static void main(String[] args) {
Calc gx = new Calc();
System.out.println(gx.x);
System.out.println(gx.add(44,3));
System.out.println(gx.selfrecur());
}
}
That works,and wow,wasn't that great.Now,i have this idea of having the constructor provide the arguments and the function's work will be to do the heavy computations.For instance in my class Kalc
class Kalc{
//** This example won't work **
private int x;
private int y;
private int z;
public Kalc(int v1,int v2,int v3){
this.x = v1;
this.y = v2;
this.z = v3;
}
public int add(){
return newObject.x + newObject.y + newObject.z;
//Gets the values of a new object and add them up
}
public int multiply(){
return newObject.x * newObject.y * newObject.z;
//Gets the values of a new object and multiply them
}
public static void main(String[] args) {
Kalc k = new Kalc(4,5,6);
System.out.println(k.add());
System.out.println(k.multiply());
}
}
I have been looking here http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html for clues but so far nothing.Is this even possible?.
Edit
class Kalc{
private int x;
private int y;
private int z;
public Kalc(int v1,int v2,int v3){
this.x = v1;
this.y = v2;
this.z = v3;
}
public int add(){
return this.x + this.y + this.z;
}
public static void main(String[] args) {
Kalc k = new Kalc(4,5,6);
System.out.println(k.add);
}
}
Error
C:\ja>javac Kalc.java
Kalc.java:17: error: cannot find symbol
System.out.println(k.add);
^
symbol: variable add
location: variable k of type Kalc
1 error
C:\ja>
Use this key word:
public int add(){
return this.x + this.y + this.z;
}
You can use this key word inside non-static methods too.
About your edit:
add is a function (and not a member) of class Kalc so you can call it as a function only:
System.out.println(k.add());
You can do the below
class Kalc{
private int x;
private int y;
private int z;
public Kalc(int v1,int v2,int v3)
{
this.x = v1;
this.y = v2;
this.z = v3;
}
public int add(){
return x+y+z;
}
public int multiply(){
return x*y*z;
}
public static void main(String[] args) {
Kalc k = new Kalc(4,5,6);
System.out.println(k.add());
System.out.println(k.multiply());
}
}
What is newObject?
You have instantiated an object with prescribed values. If you want to add them with an instance method, try this
return this.x + this.y + this.z;
I think you need to print :
System.out.println(k.add());
Instead of :
System.out.println(k.add);
as in the second case the compiler show k.add as add variable
but in the first case add() the compiler show add() as a function which you define in Kalc Class