This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
(31 answers)
Closed 4 years ago.
My application crashes because of this method. Please help :=)
public void sortedList() {
String goodLetter = "B";
for (String myItem : myArrayList) {
String myFirstChar = myItem.substring(0, 1);
if (myFirstChar != goodLetter) {
myArrayList.remove(myItem);
}
}
}
Your code will crash if:
myArrayList contains a null element (NullPointerException)
myArrayList contains the empty String (IndexOutOfBoundsException)
Any element from myArrayList does not start with "B" (ConcurrentModificationException)
For that last, and most probable, cause see the question linked by #Todd in the comments.
Additionally, in Java you should compare Strings using .equals instead of == or !=.
First, for string comparison, use String.equals() and not ==.
Second, if you want to remove objects from a list :
do a reverse browsing
or create an intermediary array containing objects to remove
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I have this
public void otis() {
println("What is Otis?");
String otis = readLine(">");
println("You said " + otis);
println(otis);
println(otis);
if (otis == "dog"){
println("you got it right!");
}
else {
println("try it again!");
otis();
}
}
But for some reason even when I respond "dog" it doesn't find a match. I can print the "otis" variable and it says "dog" but apparently that's not equivalent to "dog" somehow?
Can you try the code below? Java doesn't recognize strings as equivalent from two different instantiations even if their values are equivalent. This is because each string is a pointer, and their pointer values aren't equivalent. Try using the String.equal method!
otis.equals( "dog" )
Because == means "is the same exact object in memory", the constant string "dog" and the string it reads from the console are not the same object, even if they have the same contents. When doing comparisons in Java, always use .equals().
As a possible side effect of this, you have to be careful when comparing things that might be null in Java. If you try to do
String dog = null;
if(dog.equals("dog")) { do_something(); }
You'll end up with a NullPointerException. For this reason, many coders prefer to compare strings like this:
if("dog".equals(dog)) { do_something(); }
since you always know the constant string will not be null.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
If I set the text of a TextView in XML, like this:
<TextView
...
android:text="0" />
Can I compare that string in Java? Doing this:
private void InitializeMethod() {
A_1 = tv_1.getText().toString();
}
private void CheckAnsMethod() {
if (A_1 == "0"){
correctAns.start();
}
}else{
wrongAns.start();
}
}
causes the sound 'wrongAns.mp3' to be played...
You needs to use the String class's equals() method:
if ( "0".equals(A_1) )
"0" == A_1 will compare the values of the references pointing to where the String objects are located. In other words, it's comparing memory addresses when you really want to compare the characters in the strings.
The String class's equals() method will actually compare the strings character by character to check if they're equal.
Also, the reason I use "0".equals(A_1) instead of A_1.equals("0") is because if A_1 is ever null for whatever reason, "0".equals(A_1) will not throw a NullPointerException.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
public static void main(String[] args) {
Integer i = new Integer(4);
System.out.println(i.toString());
if (i.toString() == i.toString()) {
System.out.println("true how");
} else {
System.out.println("false how");
}
}
While executing above code, I am getting output as "false how".
Can you explain how Jvm treats this object?
toString() creates a new string object every time and your code is actually checking if both references are the same, which is never the case so it runs the else case. If you try
i.toString().equals(i.toString())
you'll get the desired output.
You must compare objects with equals() method.
i.toString().equals(i.toString())
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm in little trouble. The problem is when I'm trying to compare 2 strings(type String) operator '==' returns FALSE, but actually strings are equal.
Here's the code with its problem:
//before the following code I filled the "LinkedList <String> command" and there is
//a node with value of args[0]
String deal="";
Iterator it = commands.listIterator();
if(it.hasNext() == true)
{
if(it.next() == args[0])
{
deal += it.next();
it.hasNext();
break;
}
}
Thank You!!!
To compare two strings u should use the method equals() or equalsIgnoreCase().
in your case:
if(it.next().equals(args[0]))
the operator == returns true if the two object are the same object, same address in memory.
You use .equals when comparing two strings. So use
(it.next()).equals(args[0])
You have to use .equals method:
String deal="";
Iterator it = commands.listIterator();
if(it.hasNext() == true)
{
String next = it.next();
if(next.equals(args[0]))
{
deal += next;
break;
}
}
Be careful, .next() returns the value once and move its internal cursor to the next value.
The == cannot be used for String because the == is true if the same object instance is on both sides. The same string content can be in many String instances.
There are two ways of comparing strings.
Comparing the value of the strings (achieved using .equals ).
Comparing the actual object (achieved using == operator).
In your code you are comparing the references referred by it.next() & args[0]whereas you should compare the value of the two using it.next().equals(args[0]).
if you use == to compare two int values, then it is compare the two values, because int is primitive data type. If you use "==" to compare String object, it is check whether both String reference are referring the same String object or not. It do not consider values of the String objects.
If you want to compare values of String objects you have to use equals() of the String class. This method is comparing content of both String objects.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
i have a small of a problem. I have to String Lists with the same size and a string to compare. meaning i want to compare the string with the first list to get the index of the compared string in the list and then get another string from the other list on this index.
private String getStringOnIndex(List<String> list1, List<String> list2,String elem)
{
String elem2;
for (int i = 0; i<list1.size();i++) {
if(list1.get(i).equals(elem)){
elem2 = list2.get(i);
return elem2;
} else {
return "nope";
}
}
}
Is it wrong to compare two strings like that. or should i use the operator ==. I know the style with to string lists is not nice but its just a temporary solution. thx for any help :)
To answer your specific question on "string comparison", what you are doing is correct. String content comparison should be done using equals(). Using operator == is only checking for the equality of the reference, not the content.
For the work you are doing now, it looks like a key-value lookup to me. You may consider some redesign and, instead of storing 2 lists, make a Map<String, String>
== operator in Java compares the Object References, to compare strings you should use equals().
if (list1.get(i).matches(elem))....
always use equals method to compare two string. If you are comparing references then use == operator. Here discussion can be useful How do I compare strings in Java?
== operator work fine only if the String variable is not instanciated new keyword.
Suppose:
String s1 = "abc";
String s2 = "abc";
Then s1==s2 works good.
If:
String s1 = new String("abc");
String s2 = new String("abc");
Then you must use equals method to compare the values.
Finally, it is always better to use equals method to compare the String values.
Use the equals() method to compare the value of the object,where as == operator will compare object reference.
The problem is not equals (that is the correct method), you must remove else expression, if not you will stop always at first iteration, solution:
private String getStringOnIndex(List<String> list1, List<String> list2,String elem)
{
String elem2;
for (int i = 0; i<list1.size();i++) {
if(list1.get(i).equals(elem)){
elem2 = list2.get(i);
return elem2;
}
}
return "nope";
}