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.
Related
I have two arrays with different length, but same elements. For example
A1 = {1,2,3,null,null}
A2 = {1,2,3}
Arrays.equals gives me false, because arrays have different length. Are there any method in java that will compare only elements in method?
I don't want to use .toString
I'm trying to make compare method in my own generic stack realization.
No, because its a weird request. null does not mean 'not here', null means 'unknown / unset', that's why it throws exceptions when you interact with it: You're asking "hey, thing that has not been set yet, are you X", and there is no way to answer such a question.
That doesn't mean your code is wrong, just, you can stop looking for existing implementations. Weird requests generally aren't catered to by the core libraries (or any other). You also may want to change your mindset on null. Programming in java is a lot less aggravating if at all times a NullPointerException is a good thing. In other words, avoid using null as having any semantic meaning. If you ever write if (x == null || x.isEmpty()) you are doing it wrong. Instead, where-ever 'x' is coming from, it should hold, or be updated to ASAP, the empty string instead. So, if reading in external data (e.g. you marshalled some JSON into an object), do a 'clean' step that replaces all null values that have semantic meaning with an object that actually represents it, and for methods that return stuff, always return an object that represents what you are returning - only return null if you WANT to convey the notion that there is no result (i.e. that's not the same as 'an empty result', i.e. if any code acts like there was a result, you want it to crash).
In other words, I doubt you are asking the right question. But in case you are, you have two broad options.
First make null-less arrays then compare those as normal
One option is to make new arrays that have nulls stripped. Something like:
#SuppressWarnings("unchecked")
<T> T[] stripNulls(T[] in) {
Class<?> componentType = in.getClass().getComponentType();
return (T[]) Arrays.stream(in)
.filter(x -> x != null)
.toArray(len -> java.lang.reflect.Array.newInstance(componentType, len));
}
// which you can then use; you don't need generics for a compare,
// it wouldn't add anything at all.
boolean compare(Object[] a, Object[] b) {
return Arrays.equals(stripNulls(a), stripNulls(b));
}
Just compare in place
If it's performance sensitive that's suboptimal. A better approach would involve a little more coding:
boolean compare(Object[] a, Object[] b) {
Object ae = null, be = null;
int ai = 0, bi = 0, al = a.length, bl = b.length;
while (true) {
/* set `ae` and `be` to the next non-null element */
while (ae == null && ai < al) ae = a[ai++];
while (be == null && bi < bl) be = b[bi++];
/* Have we hit the end? */
if (ai == al && bi == bl) return true;
/* If one is at the end, but the other isn't... */
if (ai == al || bi == bl) return false;
/* check if the 2 current elements are equal */
if (!ae.equals(be)) return false;
}
}
Not a native Java Developer, but maybe this helps you?
boolean arraysEqual = Arrays.equals(Arrays.stream(a1).filter(n => n != null).toArray(), Arrays.stream(a2).filter(n => n != null).toArray())
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. :)
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
I'm having ArrayList Contains of String. I would like to check whether the character is present in the arraylist. I'm using the following code.
if(list.toString.contains(char))
{
// enter code here
}
Can i use this toString() method. What is the drawback?
It would be a really bad idea to use List.toString() and search that. Your code should probably look something like this :
Iterator it = list.getIterator();
char searchChar = 'S';
while (it.hasNext())
{
String s = (String) it.next();
if ( s.contains(searchChar) )
{
//Found the char!
}
}
No you cannot go ahead with arraylist.toString(), as it will not provide string representation of contents in String.
Better approach is to iterate over list and check, as below.
for(String detail:listString){
if(detail.contains('X')) //replace 'X' with your character
{
// do somethng
}
}
Try this,
Arrays.toString(inputList.toArray()).contains(searchValue);
list.toString() gives you a string representation of a list and thus it contains more characters then just the concatenated list elements
[stringElement1, stringElement2, ... ]
Therefore your approach will not work if the character you are looking for is , , , [ or ].
And keep in mind that this string representation is implementation specific. It might not work for other list implementations than ArrayList
I would recommend to write a method linke this:
private boolean listElementContains(List<String> list, String subString){
for(String element : list){
if(element.contains(subString)){
return true;
}
}
return false;
}
You can call toString() on any Java Object. List is an Object which contains (you guessed it) a list of other Objects. Therefore, you can also call toString() on each Object contained within the List. You should read about inheritance in Java.
In your particular case, you have a List of Strings. What you actually want to do is check each String in the List to see if the String contains a particular character. Topics you may want to read about include iteration, for loops, and for each loops.
If I understand this correctly, your code would look like this:
List<String> strings = new ArrayList<>();
//add strings to list
for (String string : strings) {
//Look for some character c
if (string.indexOf(c) >= 0) {
return true;
}
}
return false;
On the matter of list.toString, that simply returns a representation of the object as a string; it has nothing to do with the contents. Think of it like a label on a box of stuff that says "Junk." The box is labeled Junk, but you have no idea what's in it.
What's nearly certain is that toString will return a nonsense label for the object in memory. So to get at what's inside, you need to loop through the contents as shown above.
if(list.toString.contains(char))
String's contains() method won't take char as param, instead check with indexOf
Your code works, with little modifications.
A small example here:
List<String> list= new ArrayList<>();
list.add("test");
list.add("test2");
if (list.toString().indexOf('t') > -1) // True
{
System.out.println("yes there");
}
Note:
As a workaround, Make an char array and add your char in to that array and then use contains method.
I have 2 Lists token and chords. They are populated alright. But when I try to compare the 2, they always yield a false value despite of printing identical string content when printed separately in a loop. Any ideas/workarounds?
System.out.println(token.get(i).toString().equals(chords.get(j).toString()));
Both are declared as List and initialized as ArrayList();
Both contain String objects.
while (i < tokenLength) {
System.out.println("");
int j = 0;
while (j < numberOfChords) {
System.out.println(token.get(i).toString() + " compares "
+ chords.get(j).toString());
System.out.println(token.get(i).toString()
.equals(chords.get(j).toString()));
if (token.get(i).toString() == chords.get(j).toString()
&& token.get(i).toString().length() <= maxLengthOfChord) {
foundChord.add(token.get(i));
}
j++;
}
i++;
}
gives the following output :
I also tried this
System.out.println(token.get(i).toString().equals(chords.get(j).toString()));
It always yields a false returning the same result as shown in the screenshot
You did everything right up to this point:
if (token.get(i).toString() == chords.get(j).toString()
You need to use the equals method, not ==
Cannot say why it prints false, but this is definitively wrong:
if (token.get(i).toString() == chords.get(j).toString()
Change that line to
if (token.get(i).trim().equals(chords.get(j).trim())
Equality (equals()) is not the same as identity (==).
This will compare references not values.
token.get(i).toString() == chords.get(j).toString()
You have to do:
token.get(i).toString().equals(chords.get(j).toString())
I'm not sure what exactly the problem is with your current code, but I did you the favor of simplifying it a bit...
for (String t : token) {
for (String c : chords) {
System.out.println(t + " compares " + c);
System.out.println(t.equals(c));
if (t.equals(c)) {
foundChord.add(t);
}
}
}
If I'm understanding it correctly, that you should do what your current code is trying to achieve, and it should work without errors.
toString() will by default print the hashcode of the object. This hashcode is unique for all the objects and hence it never matches with hashcode of other objects and the result is false when you compare them(even if the objects are similar). You need to override the toString() method to get expected result. May be you can return values of instance variables from toString method