How to fix "Priority Queue Remove function not working " - java

I am using Priority Queue in one of my java code (Pair Class). I encountered one minor issue that uses remove function (PQ) which is not giving results. After a while ,I detect my mistake but I don't know the reason behind this issue . Can anyone explain me the logical reason behind this issue(Why last line of my code giving me false)??
I am new to this platform ,Before posting this Question I searched a lot over internet, but not getting suitable reason which would justify the above problem.
import java.util.Comparator;
import java.util.PriorityQueue;
public class PQ_IMP {
static class Pair{
int a ;
int b;
int c;
Pair(int x,int y,int z){
a=x;b=y;c=z;
}
}
public static void main(String[] args) {
PriorityQueue<Pair> name =new PriorityQueue<Pair>(new Comparator<Pair>() {
#Override
public int compare(Pair o1, Pair o2) {
return Integer.compare(o1.a,o2.a);
}
});
Pair n=new Pair(1,2,3);
name.add(n);
System.out.println(name.remove(n)); // Print true
name.add(n);
n=new Pair(1,2,3);
System.out.println(name.remove(n)); // Print False
}
}

Related

java ConcurrentHashMap with constructor as key

I am currently trying to write a little game in java lwjgl/OpenGL.
When running the code i get the value NULL when reading from some ConcurrentHashMap.
I've written a simple program to reproduce the same issue and sure enough, i could.
Let me show the code to you:
The Program consists of three classes.
The Main class:
package main;
public class Main {
private MapContainer con = new MapContainer();
public static void main(String[] args) {
new Main();
}
public Main() {
ValueContainer vc = new ValueContainer(1, 2, 3);
this.con.set(vc, "Just a String");
System.out.println(this.con.get(vc));
}
}
Then there's the MapContainer class.
It's basically a class that contains a ConcurrentHashMap and two methods to access it:
package main;
import java.util.concurrent.ConcurrentHashMap;
public class MapContainer {
private ConcurrentHashMap<ValueContainer, String> map = new ConcurrentHashMap<>();
public void set(ValueContainer key, String value) {
this.map.put(key, value);
}
public String get(ValueContainer key) {
return this.map.get(key);
}
}
At last, there's the ValueContainer.
This class just contains the three Integers x, y and z, and a Constructer to set these values.
package main;
public class ValueContainer {
public ValueContainer(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public int x, y, z;
}
So when i run the main class, i create a new ValueContainer with the values 1, 2, 3 and put it into the map Container, along with the String "Just a String".
Then i read the String with that exact Value container and print it out.
Sure enough the program works and i get "Just a String" printed in the Console.
So now there's my game:
In my game i have to access a similar ConcurrentHashMap, but i cant use the same ValueContainer to access the String, but i have to create a new one with new ValueContainer(1, 2, 3);
So obviously the ConcurrentHashMap can't give "Just a String" back, because it's not the same ValueContainer, so it gives NULL.
Here's the code of the Main class with this little modification:
package main;
public class Main {
private MapContainer con = new MapContainer();
public static void main(String[] args) {
new Main();
}
public Main() {
this.con.set(new ValueContainer(1, 2, 3), "Just a String");
System.out.println(this.con.get(new ValueContainer(1, 2, 3)));
}
}
Now my question:
Is there any way for me to use the version in the second main class, but without the issue, so that i
get printed out "Just a String" in Console?
Thank you.
Yes, quite simple.
You have to override the two methods Object.hashCode() and Object.equals() in your class ValueContainer.
Please take a look add the API-documentation of the two methods.
API
Maybe you use a IDE like Ecplise oder IntelliJ which will help you with the details.

Driver class for Array

How would I develop the driver class for this code ive written ?
Array Class:
import java.util.Scanner;
public class Array
{
Scanner sc = new Scanner(System.in);
private double[] array = new double[];
public void setArray(double[] arr)
{
//I must set a value for the array length. set by user.
//user must input data
}
public boolean isInIncreasingOrder()
{
//must test if input is in increasing order
}
public boolean isInDecreasingOrder()
{
//must test if input is in descending order
}
public double getTotal()
{
//must find the total of all input
//total +=total
}
public double getAverage()
{
//must calculate average
//average = total/array.length
}
}
I guess what I'm asking is what exactly do i call in the DriverClass and how do I do it.
Thanks
The simplest way to test a class is to have a "public static void main(String[] args)" method in the class itself.
In this "main" method, you first create an instance of the class, and then call the various methods in the class, and verify that they do what you expect. To make testing easier, you might want to print out a message after each call to the class under test, showing the expected result, the actual result, and a friendly "OK" or "FAIL" to let you see easily if the method did what you wanted.
Example:
class MyClass {
private int x = 0;
public int getX() { return x;}
public void setX(int x) { this.x = x; }
public static void main(String[] args) {
MyClass instance = new MyClass();
instance.setX(42);
int value = instance.getX();
System.out.print("Expected 42, got "+value);
if (value == 42) {
System.out.println("OK");
}
else {
System.out.println("FAIL");
}
}
}
Once you're familiar with this approach to testing, you might look into unit test frameworks such as JUnit, which provide better ways to "assert" that a particular test is passing, and to understand the results of your testing.

How to use a two class inventory program?

I have a question about my inventory program that needs a little tweaking to be functional. Essentially, I am asking the using to input the amount of a product that the individual wants to order, I want it to save in RAM, and then output the number of products and the total cost for the user. Here is my first constructor class "Item".
import java.text.*;
import java.util.*;
import javax.swing.*;
public class Item
{
public static final double SUBWOOFER_VALUE= 175.99;
public static final double TWEETER_VALUE= 34.49;
public int subOrder;
public int tweetOrder;
public double totPrice;
public int subStock;
public int tweetStock;
public Item()
{
int subStock=1000;
int tweetStock=3000;
double subPrice= (subOrder*SUBWOOFER_VALUE);
double tweetPrice= (tweetOrder*TWEETER_VALUE);
}
public void addSubOrder(int newsubOrder)
{
subOrder=newsubOrder;
}
public int getSubOrder()
{
return subOrder;
}
public void addTweetOrder(int newtweetOrder)
{
tweetOrder= newtweetOrder;
}
public int getTweetOrder()
{
return tweetOrder;
}
public void newSubStock(int newSubStock)
{
subStock= newSubStock;
newSubStock= (subStock)-(subOrder);
}
public int getsubStock()
{
return subStock;
}
public void newTweetStock(int newTweetStock)
{
tweetStock= newTweetStock;
newTweetStock= (tweetStock)-(tweetOrder);
}
public int gettweetStock()
{
return tweetStock;
}
public void totPrice(double newTotPrice, double subPrice, double tweetPrice)
{
newTotPrice= (subPrice+tweetPrice)*(.065);
totPrice= newTotPrice;
}
public double getTotPrice()
{
return totPrice;
}
public static void main (String[] args)
{
Item Order= new Item();
}//end main
}
And then here is my controller class, that controls the inputs and the outputs...
import javax.swing.*;
import java.util.*;
public class Controller
{
public static void main (String[] args)
{
Scanner myScan=new Scanner(System.in);
Item Order= new Item();
String question= "Would you like to make an order?";
String question1= "Would you like to order Subwoofers?";
String question2= "Would you like to order Tweeters?";
String question3= "How many would you like to order?";
String question4="Would you like to place another order?";
String thank= "Thank you for your order,";
System.out.println(question);
String answer= myScan.nextLine();
System.out.println(question1);
while(!answer.equalsIgnoreCase("No"))
{
String subAns= myScan.nextLine();
if(subAns.equals("Yes"))
{
System.out.println(question3);
int subOrder= myScan.nextInt();
}
System.out.println(question2);
String tweetAns= myScan.nextLine();
if(tweetAns.equals("Yes"))
{
System.out.println(question3);
int tweetOrder= myScan.nextInt();
}
else//If subAns= no then proceed to ask about tweeters.
{
tweetAns= myScan.nextLine();
if(tweetAns.equals("Yes"))//If tweeter answer = yes then proceed to ask for an amount
{
System.out.println(question3);
int tweetOrder= myScan.nextInt();
}
}break;
}//end while
System.out.println(thank);
System.out.println("Your ordered: "+ Order.getSubOrder() + " Subwoofer's and "+ Order.getTweetOrder() + " Tweeter's");
System.out.println("Your total is:"+ Order.getTotPrice());
}//end main
}//Two items
So when I input something and expect an output, I know get 0's in my output.
----jGRASP exec: java Controller
Would you like to make an order?
Yes
Would you like to order Subwoofers?
Yes
How many would you like to order?
9
Would you like to order Tweeters?
Yes
How many would you like to order?
4
Thank you for your order,
Your ordered: 0 Subwoofer's and 0 Tweeter's
Your total is:0.0
----jGRASP: operation complete.
Any help would be greatly appreciated.
you never call any of your methods to calculate update the state of Item (totPrice()) and you don't update the fields yourself ( subStock tweetStock) thus they are still their initial value because you never changed them.
On a side note it would make more sense for you to make a subwoofer and tweeter object of type Item in your controller to avoid having to double all your code in item
Also since java is pass by value, assigning to your functions arguments (such asnewSubStock= (subStock)-(subOrder); in newSubStock()) are redundant and have no purpose
I wonder why are you using swing.* import? You need to rectify your code a lot. You are using ignore case for 'NO' but not using the same for 'yes'. You have never used 'question4'. And also once you get the order in subOrder and tweetOrder, where are you using it? You need to call the methods of Item object in order to do the calculations.
Try adding "Order.addSubOrder(subOrder); & Order.addTweetOrder(tweetOrder);" after getting the orders.

Java programming test for interview

Here is a programming test used in a job interview. I find it has a very strange non-OO perspective and wonder why anyone would approach a constructor from this perspective. As a very experienced Java programmer, I immediately question the ability of the individual who wrote this code and the strange perspective of the question.
I find these strange out of context questions on interviews disturbing. I would love feedback from other experienced OO Java programmers.
Complete the Solver constructor so that a call to solveAll return a list with 2 values
including the square root and the inverse of the integer passed as parameter.
public interface MathFunction {
double calculate(double x);
}
public class Solver {
private List<MathFunction> functionList;
public Solver() {
//Complete here
}
public List<Double> solveAll(double x) {
List<Double> result = new ArrayList<Double>();
for (MathFunction function : this.functionList) {
result.add(new Double(function.calculate(x)));
}
return result;
}
}
This is testing your design patterns, by using the simplest possible method. I think this could be the Strategy (or some other behavioural pattern). See these:
http://en.wikipedia.org/wiki/Strategy_pattern
http://en.wikipedia.org/wiki/Behavioral_pattern
If you are going for a Java interview, you should be able to identify the design pattern they are hinting at and that should prevent you from being too unsettled!
To answer the question, create two classes that implement MathFunction as required, then create two instances and store them in functionList.
The point here is not 'can you do calculations in this strange way', it is 'can you identify design patterns'.
I agree that it's confusing and over-engineered.
But I do think the code is reasonably object-oriented. It's an instance of the strategy pattern. The code that generates a list of answers doesn't care how the answers are calculated - the two concerns are separated and a different calculation strategy could be applied without having to touch the code that generates the list.
To make the class more useful, these functions should be passed in from the outside (i.e. dependency injection) rather than being instantiated in the constructor.
You know the answer, I assume, but for what it's worth...
public Solver() {
functionList = new ArrayList<MathFunction>();
functionList.add(new MathFunction() {
#Override
public double calculate(double x) {
return 1d/x;
}
});
functionList.add(new MathFunction() {
#Override
public double calculate(double x) {
return Math.sqrt(x);
}
});
}
IMHO, it is indeed a strange approach. The name Solver is generic, it shouldn't implement specific operations by default. However, maybe that was part of the interview? Part one: simply fulfill the request. Part two: say that it is strange to do so.
I would say that a much nicer approach would be to have an addMathFunction(MathFunction mf) method. And if wanted, to create subclasses that extend the Solver class and add MathFunctions in their constructor.
I think they wanted you to add two items in the functionlist. Each one would implement the MathFunction interface, one for the square root and one for the inverse.
The prboblem lies in the details:
1- You have a function which returns 2 values because it does two different things, that is bad
2- If you want to have this "do-it-all" class,m it would be interesting to receive the Mathfunctions as a parameter so you can do any sort of MathFunctions, the MathFunctions would be parameterizable
Here's my solution. This is a simple illustration of a factory class.
public Solver() {
functionList = new ArrayList<MathFunction>();
MathFunction sqrt = new MathFunction() {
#Override
public double calculate(double x) {
return Math.sqrt(x);
}
};
functionList.add(sqrt);
MathFunction inverse = new MathFunction() {
#Override
public double calculate(double x) {
return 1.0D / x;
}
};
functionList.add(inverse);
}
This question shows two things:
Whether the programmer understands math terms like inverse.
Whether the programmer understands that instances of interfaces or classes can be stored in a list, and iterated over later.
While I agree that this probably isn't the best way, or most OO way to do this, I would have to assume that the point of this exercise is to see how well you understand Inheritance, Interfaces and maybe anonymous inner classes. That's the only thing I can figure.
Ok, I coded the solution to my own question. My instinct that nothing should be in the constructor seems to be correct. The functionList is not static so you need an instance to initialize it. It specifies integer so I round to integer. The inverse function is not advanced math in any way.
import java.util.ArrayList;
import java.util.List;
import java.lang.Math;
public class Solver {
private List<MathFunction> functionList = new ArrayList<MathFunction>();;
public Solver() {
// Complete here
}
public void initFunctionList() {
MathFunction functionSquareRoot = new MathFunction(){
#Override
public double calculate(double x) {
return (x<0 ? 0: Math.sqrt(x)); // maybe we need throw an exception here for negative numbers, but we'll just set it to 0
}};
MathFunction functionInverse = new MathFunction(){
#Override
public double calculate(double x) {
return (x!=0.0 ? 1/x : 0);
}
};
functionList.add(functionSquareRoot);
functionList.add(functionInverse);
}
public List<Double> solveAll(double x) {
List<Double> result = new ArrayList<Double>();
for (MathFunction function : this.functionList) {
result.add(new Double(function.calculate(x)));
}
return result;
}
}
public interface MathFunction {
double calculate(double x);
}
public class TestSolver {
/**
* #param args
*/
public static void main(String[] args) {
Solver s = new Solver();
s.initFunctionList();
System.out.println(s.solveAll(16.0));
}
}
I mislead myself the constructor can be
public Solver() {
// Complete here
MathFunction functionSquareRoot = new MathFunction(){
#Override
public double calculate(double x) {
return (x<0 ? 0: Math.sqrt(x)); // maybe we need throw an exception here for negative numbers, but we'll just set it to 0
}};
MathFunction functionInverse = new MathFunction(){
#Override
public double calculate(double x) {
return (x!=0.0 ? 1/x : 0);
}
};
functionList.add(functionSquareRoot);
functionList.add(functionInverse);
}
Somewhat contrived, seems closer to the decorator pattern to me.
Not sure what I would say during an interview but here is how I would code it:
package math;
import java.util.ArrayList;
import java.util.List;
public class DecoratorMath
{
interface MathFunction
{
double calculate(double x);
}
public static void main(String[] args)
{
DecoratorMath decoratorMath = new DecoratorMath();
decoratorMath.go();
}
public void go()
{
Solver solver = new Solver();
decorate(solver);
List<Double> results = solver.solveAll(02);
for (Double d :results)
{
System.out.println(d);
}
}
public void decorate(Solver solver)
{
solver.addFunction(new MathFunction()
{
#Override
public double calculate(double x)
{
return Math.sqrt(x);
}
});
solver.addFunction(new MathFunction()
{
#Override
public double calculate(double x)
{
return 1d/x;
}
});
}
class Solver
{
private List<MathFunction> mathFunctions = new ArrayList<MathFunction>();
public void addFunction(MathFunction mathFunction)
{
mathFunctions.add(mathFunction);
}
public List<Double> solveAll(double x)
{
List<Double> result = new ArrayList<Double>();
for (MathFunction function : mathFunctions)
{
result.add(new Double(function.calculate(x)));
}
return result;
}
}
}
Doing this all within the Constructor is just poor practice. Anyway my all-in-one solution.
import java.util.*;
import java.math.*;
//sqrt / inverse
public class Solver{
private List<MathFunction> functionList;
public interface MathFunction{
double calculate(double x);
}
class X implements MathFunction {
public double calculate(double x) {
return Math.sqrt(x);
}
}
class Y implements MathFunction {
public double calculate(double y) {
return 1/y;
}
}
public Solver(){
//here
functionList = new ArrayList<MathFunction>();
MathFunction f = (MathFunction) new X();
functionList.add(f);
MathFunction f2 = (MathFunction) new Y();
functionList.add(f2);
}
public List<Double> solveAll(double x){
List<Double> result=new ArrayList<Double>();
for (MathFunction function : this.functionList){
result.add(new Double(function.calculate(x)));
}
return result;
}
public static void main(String... args) {
System.out.println("result="+new Solver().solveAll(123));
}
}

How can I make a class implement an interface correctly?

I'm trying to make a class implement an interface correctly but seem to have hit a brick wall. I am not sure if the code I have already written is correct but it was the only way I understood how to approach the task. I have been given an interface with this information:
package mvcchords;
public interface NoteStore {
int getNextNote();
boolean hasNextNote();
void noteAdded(int midicode);
void start(int sortOrder);
}
The application displays piano keys which allow the user to click on them, and it saves the order they were clicked and the midicode of the notes for the specific sound. Then when the user clicks play, it recalls the tune in the order the notes were saved. When a user clicks on a note noteAdded is called. hasNextNote is used to check if it is the end of the saved notes or not. getNextNote is used to get the next note from the array list and start is called when the user clicks the play button. I have been told the integer sortOrder is irrelevant for this part of the task. I have been told that when the play button is clicked it should call the start method and then repeatedly call the getNextNote method until all the notes have been retrieved.
Below is the code I have written so far for a class to implement this interface;
import java.util.*;
import mvcchords.*;
public class MyNoteStore implements NoteStore {
public ArrayList<Integer> Notes;
public void noteAdded(int midicode) {
Notes.add(midicode);
}
public boolean hasNextNote(int k) {
if(Notes.get(k) != null)
return true;
else
return false;
}
public int getNextNote(int k) {
if(hasNextNote(Notes.get(k)) == true)
return Notes.get(k);
else
return 0;
}
public void start(int sortOrder) {
for(int k = 0; k < Notes.size(); k++){
hasNextNote(k);
getNextNote(k);
}
}
}
This code gives me an error saying
MyNoteStore is not abstract and does not override abstract method `hasNextNote()` in `mvcchords.NoteStore`.
I don't know where to go from here and any help would be appreciated. If further information is needed then I will do my best to clarify any points I have made.
Thank you in advance :)
While you have created methods with the correct names you need to have the correct parameters and return types as well. So in this case you need to alter:
int getNextNote(int i);
boolean hasNextNote(int k);
to remove the integer parameters.
Basically you need to keep track of the notes played back so far in the class so that you don't need to pass an integer about all the time. You could either use an Iterator or just store a integer to track the last index played. The below method uses an iterator, maybe you should try and create the one with an integer yourself.
public class MyNoteStore implements NoteStore {
ArrayList<Integer> notes = new ArrayList<Integer>();
Iterator<Integer> playbackIter;
public void noteAdded(int midicode) {
notes.add(midicode);
}
public boolean hasNextNote() {
if (playbackIter != null) {
return playbackIter.hasNext();
}
else {
return false;
}
}
public int getNextNote() {
if (playBackIter != null) {
return playBackIter.next();
}
else {
return -1;
}
}
public void start(int sortOrder) {
playBackIter = notes.iterator();
while(hasNextNote()) {
int note = getNextNote();
//play note
}
}
}
The parameters in the method are different between your implementation and the declaration in the interface.
Well,
your interface defines the methods:
int getNextNote();
boolean hasNextNote();
void noteAdded(int midicode);
void start(int sortOrder);
So,
your class has to implement them with the exact definition, which means with the same return type AND parameters. So you can either change them in the interface declaration or in the class implementation.

Categories