How to compare a String with Hashmap key? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I wana compare a String with the Key of a Hashmap.
So every time i run this code it uotputs : Not found
I'm new at Java and its surely a little thing but i need help.
Here my code
btnNewButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(!txtSearchHere.getText().isEmpty() && txtSearchHere.getText().length() > 1)
{
String value = txtSearchHere.getText();
txtSearchHere.setText("");
for(Integer key : plzHashMap.keySet())
{
if(key.toString() == value)
{
System.out.println("Matched key = " + value);
}
else
{
System.out.println("Not found");
}
}
}
}
});

For all String-comparisons in Java you should use .equals() instead of ==.
So change:
if(key.toString() == value)
to:
if(key.toString().equals(value))
The reason for this is that == is used for checking if the instances are the exact same (reference), while .equals checks for the same value.
See this SO question (among a lot of others) for more info

Try the following:
String.valueOf(key).equals(value)
And never compare String with ==, use .equals().

Firstly, compare strings using .equals(), not ==.
Secondly, it outputs Not found lots of times because that statement is inside the loop. You can move it outside the loop:
boolean found = false;
for(Integer key : plzHashMap.keySet())
{
if(key.toString().equals(value))
{
System.out.println("Matched key = " + value);
found = true;
break;
}
}
if (!found) {
System.out.println("Not found");
}
However, it would be a lot easier just to convert value to an Integer:
Integer intValue = Integer.parseInt(value);
and then just call get and hasKey - no looping required:
if (plzHashMap.hasKey(intValue)) {
System.out.println("Matched key = " + plzHashMap.get(intValue));
} else {
System.out.println("Not found");
}
Of course, you'd need to handle the case that value can't be parsed to an int.

The == operator checks for reference identity. You should use the equals methods to check for equality:
if(key.toString().equals(value))
But regardless, you're using an O(n) iteration on a hashmap which was designed to provide O(1) key lookup - why not use it?
boolean found = false;
try {
Integer integerValue = Integer.valueOf(value);
if (plzHashMap.containsKey(integerValue)) {
System.out.println("Matched key = " + value)
found = true;
}
} catch (NumberFormatException ignore) {
// value is not even a number
}
if (!found) {
System.out.println("Not found");
}

Related

Java ( Reading userinput.equalsIgnoreCase() in Arraylist)

I was writing a list of menu for my product and wanted to use a simple String (and wanted to use .equalsIgnoreCase() so that it would ignore whatever text casing it is) and compare it in ArrayList pre-coded (as i was adding a new product) using .contain(); however it still depends on text casing and I couldn't find answers. Hoping that someone would help me :).
static void AddProductCode() {
boolean print = true;
for (int i = 0; i < product.size(); i++) {
System.out.println(productcode.get(i)+" " +product.get(i)+" "+ productprice.get(i));
}
System.out.print("PRODUCT CODE : ");
code = scan.next();
code.equalsIgnoreCase(code);
boolean check = productcode.contains(code);
if(check == true){
System.out.println("CODE IS UNAVAILABLE");
AddProductCode();
}
else {
AddProduct2nd();
}
}
The List#contains(Object) compares the given object with each element of the list using the equals() method. The String#equals() method checks equality by taking the case into consideration.
So, for that you can manually implement the logic.
Replace the boolean check = productcode.contains(code); with
boolean check = false;
for (String e: productcode) {
if (e.equalsIgnoreCase(code)) {
check = true;
break;
}
}
Now, check will be true if code is present in productcode irrespective of the case. If check is false this means that code is not present in productcode

How to compare two long value at runtime in java [duplicate]

This question already has answers here:
Comparing boxed Long values 127 and 128
(4 answers)
What's the difference between ".equals" and "=="? [duplicate]
(11 answers)
Closed 7 years ago.
How to compare two long value at runtime. When I got the value of both of long type variable at runtime which same so it should be print else part but the both value is different from each other so it should be print if part.
Long dbData = 54188439.... // Got the value at run time
Long spreadSheet = 54188439.....//Got the value at run time
if(dbData != spreadSheet)
{
Log.i("","Please update your contact");
}
else
{
Log.i("","Not required");
}
Here I always got if part whatever be the condition. Please help me out.
The reason it won't work is because you are comparing the objects, not the values. See also https://stackoverflow.com/a/8968390/4890300 for a great answer.
Make use of equals operator
changed the statement from
if(dbData != spreadSheet)
to
if(!dbData.equals(spreadSheet))
When Same
public static void main(String[] args) {
Long dbData = new Long(54188439);
Long spreadSheet = new Long(54188439);
if (!dbData.equals(spreadSheet)) {
System.out.println("Please update your contact");
} else {
System.out.println("Not required");
}
}
Output
Not required
When Different
public static void main(String[] args) {
Long dbData = new Long(54188439);
Long spreadSheet = new Long(541878439);
if (!dbData.equals(spreadSheet)) {
System.out.println("Please update your contact");
} else {
System.out.println("Not required");
}
}
output
Please update your contact
if(dbData.longValue() != spreadSheet.longValue())
Edit your condition as above. It will compare 2 long values. Your exiting condition compare 2 object references.
Thanks
You should compare two instances of Long-class only with it's equals method, because == operators check the addresses, not the values.
if(!dbData.equals(spreadSheet))
{
Log.i("","Please update your contact");
}
else
{
Log.i("","Not required");
}
Use Long.compare(long x, long y)
if (Long.compare(val1, val2) == 0) {
// values are equal
} else {
// values are not equal
}
Your dbData and spreadSheet are instances of the Long class, not long primitives. You have to compare theme either using the equals() method, or compare their longValue()s. I.e.
if (!dbData.equals(spreadSheet)) {
// ...
} else {
// ...
}
or
if (dbData.longValue() != spreadSheet.longValue()) {
// ...
} else {
// ...
}
You can use below code.
Long dbData = 54188439L;// Got the value at run time
Long spreadSheet = 54188439L;//Got the value at run time
if (!dbData.equals(spreadSheet)) {
}

HashMap value and variable value match, but are not considered equal

I have a method that is called every time a player right-clicks a chest (Minecraft item), and if this block's location matches one of the values in the HashMap, it should check to see that the player's username matches the key in the HashMap. Simply put: is this location saved, and does this player who is trying to interact with it own it? My if statement to check if the player and the location match is not working correctly.
Problematic line:
if (DeathChestManager.deathChestLocation.get(playerName) == b.getLocation()) {}
HashMap and block (b) location values (what the `println()'s output):
HashMap value:
Location{world=CraftWorld{name=world},x=59.0,y=64.0,z=-30.0,pitch=0.0,yaw=0.0}
Block location value:
Location{world=CraftWorld{name=world},x=59.0,y=64.0,z=-30.0,pitch=0.0,yaw=0.0}
HashMap from the DeathChestManager class:
public static Map<String, Location> deathChestLocation = new HashMap<String, Location>();
PlayerInteract Class:
public void onPlayerInteract(PlayerInteractEvent e) {
Player p = e.getPlayer();
String playerName = p.getName();
Block b = e.getClickedBlock();
if (b != null && b.getType() == Material.CHEST) {
if (DeathChestManager.deathChestLocation.containsValue(b.getLocation())) {
e.setCancelled(true);
System.out.println(DeathChestManager.deathChestLocation.get(playerName));
System.out.println(b.getLocation());
if (DeathChestManager.deathChestLocation.get(playerName) == b.getLocation()) {
if (e.getAction() == Action.RIGHT_CLICK_BLOCK) {
b.setType(Material.AIR);
Location loc = p.getLocation();
for (final ItemStack item : DeathChestManager.inventoryContents.get(p.getName())) {
int count = 0;
for (ItemStack i : p.getInventory().getContents()) {
if (i == null) {
count++;
} else if (i.getType() == Material.AIR) {
count++;
}
}
if (count == 0) {
if (item.getType() != Material.AIR) {
p.getWorld().dropItemNaturally(loc, item);
}
} else {
if (item != null) {
p.getInventory().addItem(item);
p.updateInventory();
}
}
}
DeathChestManager dcManager = new DeathChestManager();
dcManager.endTimer(p, p.getWorld().getName());
}
} else {
MessageManager.getInstance().severe(p, "You do not own that death-chest.");
}
}
}
}
Use .equals() as opposed to == when comparing objects. == will compare the objects' addresses in memory, whereas .equals() will check to see if they have the same values. Since two objects will very rarely have the same address you should never use == except for comparing primitive types (int, char, but String is not a primitive type!) where it doesn't matter.
So you want:
if (DeathChestManager.deathChestLocation.get(playerName).equals(b.getLocation())) {}
You are comparing object references. This will return true only if they both refer to same same instance.
If you wish to compare the contents of these objects, use .equals().
You should use .equals(), not ==, when testing equality for anything other than primitives (int, boolean, etc.). This includes Strings.

How to check if the value is integer in java? [duplicate]

This question already has answers here:
Determine if object is integer
(3 answers)
Closed 6 years ago.
I'm using some API by restTemplate. The API returns a key whose type is integer.
But I'm not sure of that value, so I want to check whether the key is really an integer or not.
I think it might be a string.
What is the best way of checking if the value is really integer?
added:
I mean that some API might return value like below.
{id : 10} or {id : "10"}
If what you receive is a String, you can try to parse it into an integer, if it fails, it's because it was not an integer after all. Something like this:
public static boolean isInteger(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
Object x = someApi();
if (x instanceof Integer)
Note that if someApi() returns type Integer the only possibilities of something returned are:
an Integer
null
In which case you can:
if (x == null) {
// not an Integer
} else {
// yes an Integer
}
One possibility is to use Integer.valueOf(String)
Assuming your API return value can either be an Integer or String you can do something like this:
Integer getValue(Object valueFromAPI){
return (valueFromAPI != null ? Integer.valueOf(valueFromAPI.toString()) : null);
}

If statement with String comparison fails [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I really don't know why the if statement below is not executing:
if (s == "/quit")
{
System.out.println("quitted");
}
Below is the whole class.
It is probably a really stupid logic problem but I have been pulling my hair out over here not being able to figure this out.
Thanks for looking :)
class TextParser extends Thread {
public void run() {
while (true) {
for(int i = 0; i < connectionList.size(); i++) {
try {
System.out.println("reading " + i);
Connection c = connectionList.elementAt(i);
Thread.sleep(200);
System.out.println("reading " + i);
String s = "";
if (c.in.ready() == true) {
s = c.in.readLine();
//System.out.println(i + "> "+ s);
if (s == "/quit") {
System.out.println("quitted");
}
if(! s.equals("")) {
for(int j = 0; j < connectionList.size(); j++) {
Connection c2 = connectionList.elementAt(j);
c2.out.println(s);
}
}
}
} catch(Exception e){
System.out.println("reading error");
}
}
}
}
}
In your example you are comparing the string objects, not their content.
Your comparison should be :
if (s.equals("/quit"))
Or if s string nullity doesn't mind / or you really don't like NPEs:
if ("/quit".equals(s))
To compare Strings for equality, don't use ==. The == operator checks to see if two objects are exactly the same object:
In Java there are many string comparisons.
String s = "something", t = "maybe something else";
if (s == t) // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT
if (s > t) // ILLEGAL
if (s.compareTo(t) > 0) // also CORRECT>
Strings in java are objects, so when comparing with ==, you are comparing references, rather than values. The correct way is to use equals().
However, there is a way. If you want to compare String objects using the == operator, you can make use of the way the JVM copes with strings. For example:
String a = "aaa";
String b = "aaa";
boolean b = a == b;
b would be true. Why?
Because the JVM has a table of String constants. So whenever you use string literals (quotes "), the virtual machine returns the same objects, and therefore == returns true.
You can use the same "table" even with non-literal strings by using the intern() method. It returns the object that corresponds to the current string value from that table (or puts it there, if it is not). So:
String a = new String("aa");
String b = new String("aa");
boolean check1 = a == b; // false
boolean check1 = a.intern() == b.intern(); // true
It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.
You shouldn't do string comparisons with ==. That operator will only check to see if it is the same instance, not the same value. Use the .equals method to check for the same value.
You can use
if("/quit".equals(s))
...
or
if("/quit".compareTo(s) == 0)
...
The latter makes a lexicographic comparison, and will return 0 if the two strings are the same.
If you code in C++ as well as Java, it is better to remember that in C++, the string class has the == operator overloaded. But not so in Java. you need to use equals() or equalsIgnoreCase() for that.

Categories

Resources