Comparison of Strings [duplicate]
Possible Duplicate:
How do I compare strings in Java?
Am I am comparing strings in the wrong way? Please show me how to compare correctly? Thanks.
private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
String selectedVal = (String) jList1.getSelectedValue();
AbstractListModel model = (AbstractListModel) jList1.getModel();
int numberElements = model.getSize();
final String[] allElements = new String[numberElements + 1];
for (int i = 0; i < numberElements - 1; i++) {
String val = (String) model.getElementAt(i);
***if (selectedVal != val)*** {
allElements[i] = (String) model.getElementAt(i);
}
}
controller.deleteButtonClicked(selectedVal);
jList1.setModel(new javax.swing.AbstractListModel() {
String[] strings = allElements;
public int getSize() {
return strings.length;
}
public Object getElement开发者_StackOverflow社区At(int i) {
return strings[i];
}
});
You need to use:
selectedVal.equals( val )
!= / == only checks the reference.
Remember that the string construct "foo" is a syntactic convenience, but is really equivalent to:
char[] foo = {'f', 'o', 'o'}
new String(foo)
So the first time I type "foo" I get a new (anonymous) object of the String class and the second time I type "foo", I get a new (anonymous) object of the String class. As long as you keep that in your head, you'll remember what user968951 explained, and that is that "==" will only tell you that "foo" and "foo" are two different objects. The String class overloads "equals" so that it returns true if the characters constructing the two different String objects are the same.
"foo" == "foo" returns false because these are two different objects (that they are Strings doesn't matter to "==")
"foo".equals("foo") returns true because these are two different String objects but with the same character sequence
Remember too that objects of the String class (including anonymous objects like String literals) are not mutable, that is, they can't be changed once created. Changing a String means throwing it away and creating a new one, every time.
So the expression "foo"+"bar" does not add "bar" to "foo", but creates a "foo" String object, creates a "bar" String object, then creates a third String object that stores the result of concatenating "foo" and "bar", then gives over "foo" and "bar" to be garbage collected. If you were forced to type new String "foo" and new String "bar" and new String result, and so on, you'd probably give some thought to how expensive your code was in terms of object creation. String literals are a bit deceptive that way.
You can look at StringBuffer and StringBuilder for classes that manipulate String-like objects that can be altered instead of being thrown away and replaced with new objects with every manipulation. Honestly, though, most people just use String literals and let the garbage collector get a workout.
Hope that helps.
精彩评论