how to compare value in an array?
I have array named list which contains 12 elements. I see if value in index 0 is equal or not equal to value in index 2.
I have tried this code but it doesnt seems to work.
if ((list.get(0)==list.get(2) && list.get(1)==list.get(3))
{
System.out.println("equal")
}
If it's really an array, you want:
if (list[0] == list[2] && list[1] == list[3])
Note that if the array is of reference types, that's comparing by reference identity rather than for equality. You might want:
if (list[0].equals(list[2])) && list[1].equals(list[3]))
Although that will then go bang if any of the values is null. You might want a helper method to cope with this:
public static objectsEqual(Object o1, Object o2)
{
if (o1 == o2)
{
return true;
}
if (o1 == null || o2 == null)
{
return false;
}
return o1.equals(o2);
}
Then:
if (objectsEqual(list[0], list[2]) && objectsEqual(list[1], list[3]))
If you've really got an ArrayList instead of an array then all of the above still holds, just using list.get(x) instead of list[x] in each place.
if(list[0] == list[2] && list[1] == list[3]){
System.out.println("equal");
}
If they are strings:
if(list[0].equals(list[2]) && list[1].equals(list[3])){
System.out.println("equal");
}
You are comparing object references, not objects themselves. You need to use a method call. All classes inherit equals() from the root Object class, so it might work:
if(list.get(0).equals(list.get(2)) && list.get(1).equals(list.get(3)))
{
System.out.println("equal");
}
This article seems to be a good summary of other comparison methods available.
Related
i am confused because I need my array to be equal to the other array but I don't know how to compare them without losing their values
If both roots are null you will get an undesired result based on what you're trying to do with your second if condition.
It looks like if both roots are null you want to return true, but you're returning false. You could use just one if statement
if(thisRoot == null || otherRoot == null){
return thisRoot == null && otherRoot == null;
}
You have a bigger problem with how you're comparing the data of the two nodes.
thisRoot.getData() != otherRoot.getData()
This comparison is not what I think you're looking for. Instead you should overrride the equals method for your data objects and compare using it instead
The order of your conditions causes a problem.
if (thisRoot == null || otherRoot == null) {
return false;
}
if (thisRoot == null && otherRoot == null) {
return true;
}
The first condition will evaluate to true (and lead to return false) even if both branches are null.
You should first evaluate if both branches are null; after that, you can check the case where only one of them is null.
Pardon me if this is a stupid question.. I was wondering if there is any support for following comparison in Java:
(a, b, c .... != null) in place for :
(a != null && b != null && c != null && d ! null and so on ..)
I was trying to make code more readable as my code which is almost unreadable due to multiple condition in single statement.
code :
variable = (rest.host != null && rest.payload != null
&& rest.lockQueue != null && rest.endpoint != null ) || rest.default.setState
|| rest.scheduler.locked && rest.scheduler.queue.isFull()
&& lastPayload.getActivity.status.executing ? onExecute(rest.payload) : wait(TIME);
If your elements are in a collection, use collection.stream().allMatch(x -> x != null). Actually, there's even a predicate for that: collection.stream().allMatch(Objects::nonNull).
If your elements aren't in a collection, you can still use Arrays.asList() to create an ad-hoc list from them. So, in your case:
Arrays.asList(rest.host, rest.payload, rest.lockQueue, rest.endpoint).stream().allMatch(Objects::nonNull)
EDIT: actually, as someone mentioned in another answer, there is a method that creates a stream directly, namely Stream.of(...). So:
Stream.of(rest.host, rest.payload, rest.lockQueue, rest.endpoint).allMatch(Objects::nonNull)
You could do something like this to make sure everything is not null, if using a Java version lower than 8. Otherwise I would go with the other people's answers using streams.
private boolean checkIfNotNull( Object ... objects ) {
for(int i = 0; i < objects.length; i++) {
if(objects[i] == null)
return false;
}
return true;
}
and you could pass in all the objects that you want to check if they are null.
then you can call this in the if statement such as
if( checkIfNotNull( a, b, c, d, e, f, g ) ) {
//do stuff
}
In java 8, it could be done as next Stream.of(a, b, c, d).allMatch(Objects::nonNull), it will return true if they are all non null.
I think if you want your code more readable, you should replace your comparisons with method calls that "says" what each comparison is.
Example:
if (isAllRight(a, b, c)) {
...
}
In other cases you can break them into single comparisons and check one by one:
if (a == NUL) {
return false;
}
if (b == NULL) {
return false;
}
return true;
I have 2 string arrays in a class.
I have a TestNG class in which I need to compare the values of those arrays in a Test method. The idea is, I should loop my Test method for n number of times where n = {size of one of the arrays}
#Test(invocationCount = {fixedCount}) does not work for me, since size of the array varies.
Please let me know if I have to provide some more information.
How about to check first, if the size of the two arrays are equal? If they are not equal, then the two arrays won't be equal either.
Edit:
This is a thread about equality checking using Java. If I remember well, Arrays.equals(array1, array2) is the proper way for contained element checking, but I'm not a Java guy.
If you'd like to check the elements by hand, use iteration on the arrays (you can, since their size equals now).
bool validator(int[] array1, int[] array2)
{
if (array1 == null || array2 == null)
{
return false;
}
if (array1.length != array2.length)
{
return false;
}
for (int i = 0; i < array1.length; i++)
{
if (array1[i] != array2[i])
{
return false;
}
}
return true;
}
I'm supposed to create my own equals() method which overrides the equals(method) of the parent class. This method accepts a Counter object as its argument. In the code below, I want an easy way to determine if the Counter object argument equals the current instance of the Counter class, if that makes sense. I have achieved this in the code below by comparing the fields of each object one by one, but I want a simpler way to do it. Something that looks like this would be nice: "result = (otherCounter == new Counter(min,max) ? true : false);", but I know that's not right and it gets an error. How do I compare the equality of the variables in the two Counter objects, so that c1.equals(c2) will be false if Counter objects c1 and c2 are different?
public boolean equals(Object otherObject)
{
boolean result = true;
if (otherObject instanceof Counter)
{
Counter otherCounter = (Counter)otherObject;
result = (otherCounter.min == this.min) &&
(otherCounter.max == this.max) &&
(otherCounter.currentCount == this.currentCount) &&
(otherCounter.rolloverOccurrence == this.rolloverOccurrence) ? true : false;
}
return result;
}
Operator overloading is not possible in Java.
And to compare two object are equal or not you should use .equals() method no matter what.
Ex: obj1.equals(obj2)
It is because sometimes Java API (ex: Collections) will internally call equals method to sort the collection. So there is no simple way to compare but to use equals()
Your method is just fine like this except for the other answers you got here that state that there is not overloading of operators in Java, the thing with the result = true instead of false and commenting you remember to override hashCode if you didn't already do. Let me give you one more advise. The method can be written in some more compact way:
public boolean equals(Object obj) {
if (!(obj instanceof Counter)) {
return false;
}
Counter other = (Counter) obj;
return other.min == this.min && other.max == this.max &&
other.currentCount == this.currentCount &&
other.rolloverOccurrence == this.rolloverOccurrence;
}
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.