Java Stack Functions Diffrernce - java

I was trying to solve a light coding problem here: https://leetcode.com/problems/min-stack/
But I don't know why the code below are not identical:
public void pop() {
// if (!minStack.isEmpty() && minStack.peek() == stack.peek()){
// minStack.pop();
// }
// stack.pop();
int x = stack.pop();
if (!minStack.isEmpty() && x == minStack.peek()) {
minStack.pop();
}
}
When I use the commented code, it goes wrong. Why is that?
Thank you so much!

If you had stacks of primitives, both should work because you would be comparing contents using the ==.
I am assuming you have stack of type Integer in which case the == checks for reference equality while you should check for value equality. Using a .equals() might just solve your problem. :)

Related

i am getting wrong answer with if else block

I am comparing two strings in if else block..if it is true if block should be executed and if it is false else block should execute..but my code is always executing else block for both true & false condition..here is my code
if(deckey==keystr)
{
.
.
}
else
{
System.out.println("your unauthorised person");
System.exit(0);
}
my deckey is containing string value abc123 and for keystr i am getting the value from this which is also abc123(i am getting through arraylist)..
ArrayList<Integer> listfkey= new ArrayList<Integer>();
String keystr=" ";
for (int i = 0; i < listfkey.size(); i++) {
dech=(char)listfkey.get(i).intValue();
keystr+=dech;
}
please help me out..
Strings need to be tested for equality using the .equals method:
deckey.equals(keystr)
Not the == operator, which tests if two string instances are the same:
deckey==keystr
primatives are a different matter, but with Java objects, == will only return true if the object is being compared to itself (same memory location). For Objects, use the equals method or the Comparator interface
== is use for compare memory location, it will be right on some primitive data
String is object, so for compare it we need to use .equals() method
It come from Comparator

Do I have this written properly? .equals AND !.equals if statement

FIXED. To get the statement to evaluate the way I wanted it to I had to write it this way:
public static Boolean pushCard(String S1, String S2) {
Boolean result = false;
if ((S1.equals("fire") || S1.equals("wind") || S1.equals("water")))
if (!S2.equals("fire") && (!S2.equals("water") && (!S2.equals("fire"))))
result = true;
return result;
} //end push card method
I can not tell if this comparison is causing issues. I was using == instead of .equals but then I learned that it was the wrong way to write it. Thanks for the help!
public static Boolean pushCard(String S1, String S2) {
Boolean result = false;
if ((S1.equals("fire") || S1.equals("wind") || S1.equals("water")))
if (!S2.equals("fire") || (!S2.equals("water") || (!S2.equals("fire"))))
result = true;
return result;
} //end push card method
Syntactically, your code will compile just fine, and the way you use .equals() method to compare strings is correct. Your use of the ! operator is also correct.
There is no guarantee that your code will not have logical errors though.
The only problem I can see you have "fire" mentioned twice in your second if statement. Otherwise, any problems you might be having could be related to your logic being wrong, since your syntax is pretty much correct and your usage is proper.
It is unclear what you're asking. The second if will always be true. You probably need :
if ((S1.equals("fire") || S1.equals("wind") || S1.equals("water")))
if (!S2.equals("fire") && (!S2.equals("water") && (!S2.equals("wind"))))
result = true;
public static Boolean pushCard(String S1, String S2)
{
Boolean result = false;
if (S1.equals("fire") || S1.equals("wind") || S1.equals("water"))
{
(!S2.equals("fire") || !S2.equals("water"))
result = true;
}
return result;
}
/end push card method
you had an extra pair of brackets in the first if statement.
I believe an if statement needs brackets {} when the code inside it is larger than one line.
your second if statement can be altered to just !S2.equals("fire") || !S2.equals("water")

If else statements inside jsp

I have a following problem - if else statements do not work in JSP, and to be honest I have no idea why. Basically I try to change the placeName depending on what number is stored in a string called place. After printing the values in the browser I can see the value is not changed. I am sure it is something simple but... Maybe some one had similar problem before?
<%
//requests the strings sent by previous page
String year = request.getParameter("year");
String place = request.getParameter("place");
out.print(year);
out.print(place);
String year2 = request.getParameter("year2");
String place2 = request.getParameter("place2");
//out.print(year2);
//out.print(place2);
if (place == "1")
{
placeName = "Belmullet";
}
else if (place == "2")
{
placeName = "Birr";
}
...more statements here...
else if (place == "15")
{
placeName = "Shannon airport";
};
%>
change the if condition:
if (place == "1") {
}
by
if ("1".equals(place)) {
}
and the same way for the other if conditions.
This SO question may helps you to learn the difference between == and equals().
It's because you're comparing Strings using ==. Instead, use the .equals() method.
The == operator tests to see if two object references refer to the exact same instance of an object.
The .equals() tests to see if the two objects being compared to each other are equivalent.

String array[0] don't pass at the if

Hello everybody I have a question:
I have a array
String[] parte
and I need of the first value of the array so I did:
String verifica = parte[0] // It can be N (for Name) L (for List) and E (for Error)
Why if I run this code and I know that "verifica" is L
if (verifica == "L") { //If code
} else { //Else code
}
it returned to me always the Else code
ThankYou sooooo much
-Matteo
Comparing Strings in Java must be done with String.equals():
if (verifica.equals("L")) { //If code
What you were trying to do was comparing two distinct objects, and not their contents.
You need to use:
if (verifica.equals("L")) { //If code
} else { //Else code
}
instead of '=='. '==' in Java checks for object identity in memory, where the functionality you're needing here is to compare String values. Took me experiencing this error to realize the difference (I come from a C# background) in Java as well.
Use the equals operator for strings:
if (verifica.equals("L"))
You want if (verifica.equals("L")) or if (verifica.compareTo("L") == 0). == is not a reliable operator for comparing strings.

Implementing the equals method in java

This is my implementation of the equals class for a Coor class which is just contains 2 ints x and y. would this be the proper way of implementing this method?
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != this.getClass()) {
return false;
}
Coor temp = (Coor) obj;
if (temp.x == this.x && temp.y == this.y) {
return true;
} else {
return false;
}
}
You could add one more check for reflexive equality (equal to self):
public boolean equals(Object obj) {
// Reflexive equality: did I get passed myself?
if(this == obj){
return true;
}
if (obj == null || obj.getClass() != this.getClass()) {
return false;
}
Coor temp = (Coor) obj;
return temp.x == this.x && temp.y == this.y;
}
Yes, it would.
Also be sure to override your hashCode() method--never override one without doing the other as well, it will confuse the hell out of your collections.
Your case could use a hash where it simply shifts one of the ints 32 bits and adds it to the other creating a completely unique long (a perfect hash function in this case--no collisions)
Seems ok.
For brevity sake, you can do:
return temp.x == this.x && temp.y == this.y
Instead of
if (temp.x == this.x && temp.y == this.y) {
return true;
} else {
return false;
}
Also, please keep in mind the Object Contract (seriously!).
See the accepted answer here:
What issues should be considered when overriding equals and hashCode in Java?
This can save you a huge about of headache in the future.
Check this out:
http://www.javapractices.com/topic/TopicAction.do?Id=17
If that article is too much detail, then the short of it is:
Your implementation is correct, but you should keep some other things in mind:
You will also have to implement hashCode.
equals will no longer commpare the object's identity. Doesn't sound like that's a problem for you.
You could add the #Override annotation to your equals method.
Here’s a more straightforward way:
public boolean equals(Object other) {
return other instanceof Coor
&& ((Coor) other).x == x
&& ((Coor) other).y == y
}
I believe this would work, at a quick glance. I say this because:
It handles a null/improper types well.
Performing x.equals(y) would yield the same result as y.equals(x).
Performing x.equals(x) would return true.
Performing x.equals(y) == true and y.equals(z) == true implies that x.equals(z) == true
This question has certainly been asked many times before though. See here: Overriding equals and hashCode in Java. A book called Effective Java discusses this topic in great detail too, and the particular chapter is linked off of there.
There's only one source to read for how to override equals and hashCode: chapter 3 of Joshua Bloch's "Effective Java".
If you have a good IDE, like IntelliJ, it'll generate equals and hashCode the right way for you.

Categories