Error while using ternary operator - java

I'm writing my Code with Eclipse Juno and I'm using a hash table to set my dataImportObject depending on the entries in it.
Could anyone please tell me whats wrong about this:
ht is my hashTable with <String, Integer> pairs in it
(ht.containsKey("DEVICE_ADDRESS")) ?
dataImportObject.setDevice_Address(dataitems[ht.get("DEVICE_ADDRESS")]) :
dataImportObject.setDevice_Address("");

Could anyone please tell me whats wrong about this
Two things:
The conditional operator can't be used as a statement on its own, only as an expression
I assume these set methods have void return types, so they can't appear as operands in the conditional operator
Three options:
Use an if statement:
if (ht.containsKey("DEVICE_ADDRESS")) {
dataImportObject.setDevice_Address(dataitems[ht.get("DEVICE_ADDRESS")]));
} else {
dataImportObject.setDevice_Address("");
}
Use the conditional operator inside the setDevice_Address call, or even clearer, beforehand:
String address = ht.containsKey("DEVICE_ADDRESS")
? dataitems[ht.get("DEVICE_ADDRESS")] : "";
dataImportObject.setDevice_Address(address);
If you know that your hashtable won't have any null values, you can avoid the double lookup:
Integer index = ht.get("DEVICE_ADDRESS");
String address = index == null ? "" : dataitems[index];
dataImportObject.setDevice_Address(address);

You can't set the return type of ternary condition to void.
Use if else for that.
Possible duplicate

Related

Assertj verify that a field of each items in a collection is always null

I'm looking for a solution to check that each items in a collection have the field expectedNullField null.
The following doesn't work:
assertThat(aCollection).extracting("expectedNullField").isNull();
Note that the following works as expected:
assertThat(aCollection).extracting("expectedNotNullField").isNotNull();
Anybody to help me ?
Thanks.
If you know the size (let's say it is 3) you can use
assertThat(aCollection).extracting("expectedNullField")
.containsOnly(null, null, null);
or if you are only interested in checking that there is a null value
assertThat(aCollection).extracting("expectedNullField")
.containsNull();
Note that you can't use:
assertThat(aCollection).extracting("expectedNullField")
.containsOnly(null);
because it is ambiguous (containsOnly specifying a varargs params).
I might consider adding containsOnlyNullElements() in AssertJ to overcome the compiler error above.
You can use a Condition
Condition<YourClass> nullField = new Condition<>("expecting field to be null") {
#Override
public boolean matches(YourClass value) {
return value.getField() == null;
}
};
assertThat(aCollection).have(nullField);
which might be easier to read than the other solution
assertThat(aCollection).filteredOn("expectedNullField", not(null)).isEmpty();

Java: compare String var to int

I request variable from the server (String xxx) and receive it properly (it equals 1).
Then I want to use it in 'if' statement, so I do :
if(xxx.equals(String.valueOf(1)))
but it doesn't work the way it supposed to be - it should be equal, but it works as it is not.
I'm out of solutions. What am I doing wrong ?
See what happens after trime xxx
if(xxx.trim().equals(String.valueOf(1)))
Try this:
if(Integer.valueOf(xxx.trim()) == 1)
Rather compare them as integers than as strings.
try this:
if (xxx.trim().equalsIgnoreCase(intValue+"") {
}
or
if (xxx.trim().equalsIgnoreCase("1")) {
}

How can I use more than one comparison with the .equals function or is there another function that I can use to check?

BTW, this is only a short version of my code, the only problem I have is from .equalsIgnoreCase over. I have tried the pipe operator || and that has not worked for "or" either. Let me know, thanks. Its in Java too.
if(sWord.substring(0,sWord.length()).equalsIgnoreCase("ch","sh","s","x","z"
{
lblPluralOutput.setText(sWord + "es");
}
}
No, you cannot do it directly like that. Put all possible values in an array and check your string is in that array or not.
String[] items ={"ch","sh","s","x","z"};
for (String item : items) {
if (sWord.substring(0,sWord.length()).equalsIgnoreCase(item)) {
lblPluralOutput.setText(sWord + "es");
break;
}
}
More over sWord.substring(0,sWord.length()) again gives you same string back. Is it a typo ?
Those functions only take one parameter.
If you want to check whether a string is equal to either of two things, you need to check separately:
if (a.equals(b) || a.equals(c))
You can't use String#equalsIgnoreCase(Str) cause only receives one parameter. But you can
make your util method.
Something like this. We can make it generic.
public final class UtilClass{
private UtilClass(){}
public static <T> boolean isSomeOneEquals(T myParam, T ... a){
return Arrays.asList(a).contains(myParam);
}
}
So in your example just put:
UtilClass.isSomeOneEquals( sWord.substring(someIndex,sWord.length()).toLowerCase(), "ch","sh","s","x","z" );

Searching through a collection of an array list pair [duplicate]

This question already has answers here:
How to compare two java objects [duplicate]
(5 answers)
Closed 9 years ago.
I am trying to search through a collection of an ArrayList if pairs. What I want to be able to do, is to go through the collection and find the first value in a pair and return the second value of that pair. The problem I am having is that the check I have to find the first value doesn't seem to be working, so every time I search, I end up returning null. I know that the problem exists with my if statement, but I cannot seem to sort out what it is I am doing wrong. Since this is a homework assignment, I can't show all the code to my pair class, or my pair list class, but I can show you the method I have for searching the first value:
public S findFirst(F firstValue) {
Iterator<Pair> myIter = this.iterator();
S tmp2 = null;
while (myIter.hasNext()) {
Pair tmp1 = myIter.next();
if (tmp1.getFirst() == firstCall) {
tmp2 = (S) tmp1.getSecond();
}
}
return tmp2;
}
If I throw in an else statement that just calls what I am attempting to do in my if check, like this:
else{
tmp2 = (S) tmp1.getSecond();
}
then whenever I test for the first value, I get the second value, so I know I am at least on the correct path, but I am assuming that I am doing something wrong with what I am checking for in my if statement. Does anyone know how I can correctly do this, (and please bear in mind that this is homework, so a guide to how to figure this out is far more valuable to me than just some random answer, I want to learn, not just be given an answer) Thanks in advance!
Don't use == to compare objects. Override and use equals().
I think
if (tmp1.getFirst() == firstCall)
should probably say
if (tmp1.getFirst().equals(firstValue))
The important difference is that == checks whether two expressions refer to the exact same object. You're more interested in knowing whether your two expressions actually refer to objects that are equal.
Try this:
if (tmp1.getFirst().equals(firstValue))
instead of
if (tmp1.getFirst() == firstCall)
Also you can override your own equals method.
You should never use == to compare objects.
Check How to compare two java objects
What Matt says, (don't use == ) but I think a bigger problem is that you don't return the 'first' encounter.... your if statement should look like:
public S findFirst(F firstValue) {
Iterator<Pair> myIter = this.iterator();
while (myIter.hasNext()) {
Pair tmp1 = myIter.next();
if (firstValue.equals(tmp1.getFirst())) {
return (S) tmp1.getSecond();
}
}
return null;
}

Java Ternary Operator inside ternary operator, how evaluated?

Very basic question I suppose, I just wanted to know how this code is read:
return someboolean ? new someinstanceofsomething() : someotherboolean ? new otherinstance() : new third instance();
I guess now as I'm writing it I kind of understand the statement. It returns option one if true but then does another boolean check if false and returns one of the two remaining options? I'm going to continue to leave this question because I have not seen it before and maybe others have not as well.
Could you go on indefinitely with ternary inside of ternary operations?
Edit: Also why is this/is this not better for code than using a bunch of if statements?
It is defined in JLS #15.25:
The conditional operator is syntactically right-associative (it groups right-to-left). Thus, a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).
In your case,
return someboolean ? new someinstanceofsomething() : someotherboolean ? new otherinstance() : new third instance();
is equivalent to:
return someboolean ? new someinstanceofsomething() : (someotherboolean ? new otherinstance() : new third instance());
Ternary operators are right-associative. See assylias's answer for the JLS reference.
Your example would translate to:
if (someboolean) {
return new someinstanceofsomething();
} else {
if (someotherboolean) {
return new otherinstance();
} else {
return new thirdinstance()
}
}
And yes, you can nest these indefinitely.

Categories