/ 猿问

# .equals()方法和==相等判断有什么区别？Leetcode 155中的问题

2019-02-23 16:53:32

``````if(minstack.peek()==(stack.peek())
``````

``````Input:
["MinStack","push","push","push","push","pop","getMin","pop","getMin","pop","getMin"]
[[],[512],[-1024],[-1024],[512],[],[],[],[],[],[]]
Output:
["constructor","null","null","null","null","null","-1024","null","-1024","null","-1024"]
Expected:
["constructor","null","null","null","null","null","-1024","null","-1024","null","512"]``````

``````if(minstack.peek().equals(stack.peek()))
``````

``````public class MinStack {
Stack<Integer> minstack = new Stack<Integer>();
Stack<Integer> stack = new Stack<Integer>();

public MinStack() {
}

public void push(int x) {
if(minstack.empty() || x <= minstack.peek())
minstack.push(x);
stack.push(x);
}
public void pop() {
**if(minstack.peek()==(stack.peek()))**
minstack.pop();
stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin(){
return minstack.peek();
}
}
``````

## 4 回答

``````public class MinStack {
Stack<Integer> minstack = new Stack<Integer>();
Stack<Integer> stack = new Stack<Integer>();

public MinStack() {
}

public void push(int x) {
Integer val = new Integer(x);
if(minstack.empty() || val <= minstack.peek())
minstack.push(val);
stack.push(val);
}
public void pop() {
if(minstack.peek()==(stack.peek()))
minstack.pop();
stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin(){
return minstack.peek();
}
}``````

==是比引用，equals比的是值。

==是比较两个字符串引用的地址是否相同，即是否指向同一个对象，而equals方法则比较字符串的内容是否相同。

``````String a = "abc";
String b = "abc";
``````

a == b返回true，a.equals(b)同样返回true。

``````String a = "abc";
String b = new String("abc");
``````

• 4 回答
• 0 关注
• 566 浏览

0/150