class Solution {
private Integer[][] memory = //whaterver, It doesn't matter.
public int leetcode(int[] array) {
return Math.max(dfs(0, 0), dfs(0, 1));
}
int dfs(int status1, int status2) {
if (status1 == Integer.MAX_VALUE || status2 == Integer.MAX_VALUE) {
return 0;
}
if (memory[status1][status2] != null) {
return memory[status1][status2];
} else {
memory[status1][status2] = calculate() + Math.max(dfs(status1 + 1, status2), dfs(status1 + 1, status2 + 1));
return memory[status1][status2];
}
}
Integer calculate() {
//...
}
}
As shown in the above java code, in java, you can use null to judge whether an element in the array has memorized a certain value. If memorized, you can use it directly. If not, you need to do some calculations and then store the calculated value.
In Kotlin, since IntArray does not accept null, is there any good way to achieve similar operations?
thanks a lot.
You can make a variable accept nulls by using ?
In Kotlin, the type system distinguishes between references that can hold null (nullable references) and those that cannot (non-null references). For example, a regular variable of type String cannot hold null:
var a: String = "abc" // Regular initialization means non-null by default
a = null // compilation error
To allow nulls, you can declare a variable as nullable string, written String?:
var b: String? = "abc" // can be set null
b = null // ok
print(b)
You want an Int array that accepts null so write:-
fun main() {
val emptyArray : Array<Int?> = arrayOfNulls(0)
println(emptyArray.size) // 0
}
Check this documentation on null safety for all the details.Comment for any follow up query
Hope you found this answer useful, if so please accept it by clicking the ✔(tick symbol) next to it. Have a nice day :)
How can I check whether a string is not null and not empty?
public void doStuff(String str)
{
if (str != null && str != "**here I want to check the 'str' is empty or not**")
{
/* handle empty string */
}
/* ... */
}
What about isEmpty() ?
if(str != null && !str.isEmpty())
Be sure to use the parts of && in this order, because java will not proceed to evaluate the second part if the first part of && fails, thus ensuring you will not get a null pointer exception from str.isEmpty() if str is null.
Beware, it's only available since Java SE 1.6. You have to check str.length() == 0 on previous versions.
To ignore whitespace as well:
if(str != null && !str.trim().isEmpty())
(since Java 11 str.trim().isEmpty() can be reduced to str.isBlank() which will also test for other Unicode white spaces)
Wrapped in a handy function:
public static boolean empty( final String s ) {
// Null-safe, short-circuit evaluation.
return s == null || s.trim().isEmpty();
}
Becomes:
if( !empty( str ) )
Use org.apache.commons.lang.StringUtils
I like to use Apache commons-lang for these kinds of things, and especially the StringUtils utility class:
import org.apache.commons.lang.StringUtils;
if (StringUtils.isNotBlank(str)) {
...
}
if (StringUtils.isBlank(str)) {
...
}
Just adding Android in here:
import android.text.TextUtils;
if (!TextUtils.isEmpty(str)) {
...
}
To add to #BJorn and #SeanPatrickFloyd The Guava way to do this is:
Strings.nullToEmpty(str).isEmpty();
// or
Strings.isNullOrEmpty(str);
Commons Lang is more readable at times but I have been slowly relying more on Guava plus sometimes Commons Lang is confusing when it comes to isBlank() (as in what is whitespace or not).
Guava's version of Commons Lang isBlank would be:
Strings.nullToEmpty(str).trim().isEmpty()
I will say code that doesn't allow "" (empty) AND null is suspicious and potentially buggy in that it probably doesn't handle all cases where is not allowing null makes sense (although for SQL I can understand as SQL/HQL is weird about '').
str != null && str.length() != 0
alternatively
str != null && !str.equals("")
or
str != null && !"".equals(str)
Note: The second check (first and second alternatives) assumes str is not null. It's ok only because the first check is doing that (and Java doesn't does the second check if the first is false)!
IMPORTANT: DON'T use == for string equality. == checks the pointer is equal, not the value. Two strings can be in different memory addresses (two instances) but have the same value!
Almost every library I know defines a utility class called StringUtils, StringUtil or StringHelper, and they usually include the method you are looking for.
My personal favorite is Apache Commons / Lang, where in the StringUtils class, you get both the
StringUtils.isEmpty(String) and the
StringUtils.isBlank(String) method
(The first checks whether a string is null or empty, the second checks whether it is null, empty or whitespace only)
There are similar utility classes in Spring, Wicket and lots of other libs. If you don't use external libraries, you might want to introduce a StringUtils class in your own project.
Update: many years have passed, and these days I'd recommend using Guava's Strings.isNullOrEmpty(string) method.
This works for me:
import com.google.common.base.Strings;
if (!Strings.isNullOrEmpty(myString)) {
return myString;
}
Returns true if the given string is null or is the empty string.
Consider normalizing your string references with nullToEmpty. If you
do, you can use String.isEmpty() instead of this method, and you won't
need special null-safe forms of methods like String.toUpperCase
either. Or, if you'd like to normalize "in the other direction,"
converting empty strings to null, you can use emptyToNull.
There is a new method in java-11: String#isBlank
Returns true if the string is empty or contains only white space codepoints, otherwise false.
jshell> "".isBlank()
$7 ==> true
jshell> " ".isBlank()
$8 ==> true
jshell> " ! ".isBlank()
$9 ==> false
This could be combined with Optional to check if string is null or empty
boolean isNullOrEmpty = Optional.ofNullable(str).map(String::isBlank).orElse(true);
String#isBlank
How about:
if(str!= null && str.length() != 0 )
Returns true or false based on input
Predicate<String> p = (s)-> ( s != null && !s.isEmpty());
p.test(string);
Use Apache StringUtils' isNotBlank method like
StringUtils.isNotBlank(str)
It will return true only if the str is not null and is not empty.
For completeness: If you are already using the Spring framework, the StringUtils provide the method
org.springframework.util.StringUtils.hasLength(String str)
Returns:
true if the String is not null and has length
as well as the method
org.springframework.util.StringUtils.hasText(String str)
Returns:
true if the String is not null, its length is greater than 0, and it does not contain whitespace only
You can use the functional style of checking:
Optional.ofNullable(str)
.filter(s -> !(s.trim().isEmpty()))
.ifPresent(result -> {
// your query setup goes here
});
You should use org.apache.commons.lang3.StringUtils.isNotBlank() or org.apache.commons.lang3.StringUtils.isNotEmpty. The decision between these two is based on what you actually want to check for.
The isNotBlank() checks that the input parameter is:
not Null,
not the empty string ("")
not a sequence of whitespace characters (" ")
The isNotEmpty() checks only that the input parameter is
not null
not the Empty String ("")
If you don't want to include the whole library; just include the code you want from it. You'll have to maintain it yourself; but it's a pretty straight forward function. Here it is copied from commons.apache.org
/**
* <p>Checks if a String is whitespace, empty ("") or null.</p>
*
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
*
* #param str the String to check, may be null
* #return <code>true</code> if the String is null, empty or whitespace
* #since 2.0
*/
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
test equals with an empty string and null in the same conditional:
if(!"".equals(str) && str != null) {
// do stuff.
}
Does not throws NullPointerException if str is null, since Object.equals() returns false if arg is null.
the other construct str.equals("") would throw the dreaded NullPointerException. Some might consider bad form using a String literal as the object upon wich equals() is called but it does the job.
Also check this answer: https://stackoverflow.com/a/531825/1532705
Simple solution :
private boolean stringNotEmptyOrNull(String st) {
return st != null && !st.isEmpty();
}
As seanizer said above, Apache StringUtils is fantastic for this, if you were to include guava you should do the following;
public List<Employee> findEmployees(String str, int dep) {
Preconditions.checkState(StringUtils.isNotBlank(str), "Invalid input, input is blank or null");
/** code here **/
}
May I also recommend that you refer to the columns in your result set by name rather than by index, this will make your code much easier to maintain.
You can use StringUtils.isEmpty(), It will result true if the string is either null or empty.
String str1 = "";
String str2 = null;
if(StringUtils.isEmpty(str)){
System.out.println("str1 is null or empty");
}
if(StringUtils.isEmpty(str2)){
System.out.println("str2 is null or empty");
}
will result in
str1 is null or empty
str2 is null or empty
I've made my own utility function to check several strings at once, rather than having an if statement full of if(str != null && !str.isEmpty && str2 != null && !str2.isEmpty). This is the function:
public class StringUtils{
public static boolean areSet(String... strings)
{
for(String s : strings)
if(s == null || s.isEmpty)
return false;
return true;
}
}
so I can simply write:
if(!StringUtils.areSet(firstName,lastName,address)
{
//do something
}
In case you are using Java 8 and want to have a more Functional Programming approach, you can define a Function that manages the control and then you can reuse it and apply() whenever is needed.
Coming to practice, you can define the Function as
Function<String, Boolean> isNotEmpty = s -> s != null && !"".equals(s)
Then, you can use it by simply calling the apply() method as:
String emptyString = "";
isNotEmpty.apply(emptyString); // this will return false
String notEmptyString = "StackOverflow";
isNotEmpty.apply(notEmptyString); // this will return true
If you prefer, you can define a Function that checks if the String is empty and then negate it with !.
In this case, the Function will look like as :
Function<String, Boolean> isEmpty = s -> s == null || "".equals(s)
Then, you can use it by simply calling the apply() method as:
String emptyString = "";
!isEmpty.apply(emptyString); // this will return false
String notEmptyString = "StackOverflow";
!isEmpty.apply(notEmptyString); // this will return true
If you are using Spring Boot then below code will do the Job
StringUtils.hasLength(str)
With Java 8 Optional you can do:
public Boolean isStringCorrect(String str) {
return Optional.ofNullable(str)
.map(String::trim)
.map(string -> !str.isEmpty())
.orElse(false);
}
In this expression, you will handle Strings that consist of spaces as well.
To check if a string is not empty you can check if it is null but this doesn't account for a string with whitespace. You could use str.trim() to trim all the whitespace and then chain .isEmpty() to ensure that the result is not empty.
if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }
I would advise Guava or Apache Commons according to your actual need. Check the different behaviors in my example code:
import com.google.common.base.Strings;
import org.apache.commons.lang.StringUtils;
/**
* Created by hu0983 on 2016.01.13..
*/
public class StringNotEmptyTesting {
public static void main(String[] args){
String a = " ";
String b = "";
String c=null;
System.out.println("Apache:");
if(!StringUtils.isNotBlank(a)){
System.out.println(" a is blank");
}
if(!StringUtils.isNotBlank(b)){
System.out.println(" b is blank");
}
if(!StringUtils.isNotBlank(c)){
System.out.println(" c is blank");
}
System.out.println("Google:");
if(Strings.isNullOrEmpty(Strings.emptyToNull(a))){
System.out.println(" a is NullOrEmpty");
}
if(Strings.isNullOrEmpty(b)){
System.out.println(" b is NullOrEmpty");
}
if(Strings.isNullOrEmpty(c)){
System.out.println(" c is NullOrEmpty");
}
}
}
Result:
Apache:
a is blank
b is blank
c is blank
Google:
b is NullOrEmpty
c is NullOrEmpty
Simply, to ignore white space as well:
if (str == null || str.trim().length() == 0) {
// str is empty
} else {
// str is not empty
}
Consider the below example, I have added 4 test cases in main method. three test cases will pass when you follow above commented snipts.
public class EmptyNullBlankWithNull {
public static boolean nullEmptyBlankWithNull(String passedStr) {
if (passedStr != null && !passedStr.trim().isEmpty() && !passedStr.trim().equals("null")) {
// TODO when string is null , Empty, Blank
return true;
}else{
// TODO when string is null , Empty, Blank
return false;
}
}
public static void main(String[] args) {
String stringNull = null; // test case 1
String stringEmpty = ""; // test case 2
String stringWhiteSpace = " "; // test case 3
String stringWhiteSpaceWithNull = " null"; // test case 4
System.out.println("TestCase result:------ "+nullEmptyBlankWithNull(stringWhiteSpaceWithNull));
}
}
BUT test case 4 will return true(it has white space before null) which is wrong:
String stringWhiteSpaceWithNull = " null"; // test case 4
We have to add below conditions to make it work propper:
!passedStr.trim().equals("null")
If you use Spring framework then you can use method:
org.springframework.util.StringUtils.isEmpty(#Nullable Object str);
This method accepts any Object as an argument, comparing it to null and the empty String. As a consequence, this method will never return true for a non-null non-String object.
To check on if all the string attributes in an object is empty(Instead of using !=null on all the field names following java reflection api approach
private String name1;
private String name2;
private String name3;
public boolean isEmpty() {
for (Field field : this.getClass().getDeclaredFields()) {
try {
field.setAccessible(true);
if (field.get(this) != null) {
return false;
}
} catch (Exception e) {
System.out.println("Exception occurred in processing");
}
}
return true;
}
This method would return true if all the String field values are blank,It would return false if any one values is present in the String attributes
I've encountered a situation where I must check that "null" (as a string) must be regarded as empty. Also white space and an actual null must return true.
I've finally settled on the following function...
public boolean isEmpty(String testString) {
return ((null==testString) || "".equals((""+testString).trim()) || "null".equals((""+testString).toLowerCase()));
}
I am working on a solution to a very common Java problem involving Strings. I would like to write a method to see if a string is a permutation (anagram) of another.
My solution is this: I am writing a method that takes two Strings. I iterate through one String and put the characters that are found into a HashMap, where the key is the letter, and the value is the number of occurrences of that letter, as an int. Once I finish iterating through the first String, I iterate through the second String and decrement the values of each character found in the same HashMap.
Once a key reaches zero, I remove the key/value pair altogether from the HashMap. Once I finish iterating through the second String, I then merely check to see if the HashMap is empty. If it is, then the two Strings are permutations/anagrams of one another, otherwise the method returns false.
My method is as follows:
public boolean checkPermutation (String stringA, String stringB) {
if (stringA.length() != stringB.length()) {
return false;
}
else {
HashMap alpha = new HashMap();
for (int i = 0; i < stringA.length(); i++) {
if (!alpha.containsKey(stringA.charAt(i))) {
alpha.put(stringA.charAt(i), 0);
}
else {
Integer value = (Integer) alpha.get(stringA.charAt(i));
int newValue = value.intValue();
alpha.put(stringA.charAt(i), newValue++);
}
}
for (int j = 0; j < stringB.length(); j++) {
if (alpha.containsKey(stringB.charAt(j))) {
Integer value = (Integer) alpha.get(stringA.charAt(j));
int newValue = value.intValue();//null pointer exception here
if (newValue > 1) {
alpha.put(stringB.charAt(j), newValue--);
}
else {
alpha.remove(stringB.charAt(j));
}
}
}
if (alpha.isEmpty())
return true;
else
return false;
}
}
My problem is that my solution is case-sensitive (i.e. If I enter "Hello", and "oellH", I get a null pointer exception). I would like to make this solution case-insensitive, and figure out why I am getting a Null-Pointer Exception. Can anyone see what I am doing wrong?
As a minor follow up question, is such a solution of type O(n) despite there being two for-loops?
Integer value = (Integer) alpha.get(stringA.charAt(j));
Try changing stringA to stringB.
Integer value = (Integer) alpha.get(stringB.charAt(j));
Because if you give different String which dont have same characters in it the value will be null and it will through NPE.
Change both string to lowercase or uppercase.
stringA= stringA.toLowercase();
stringB= stringB.toLowercase();
The null pointer exception is thrown because you are checking for char of stringB in hashmap and then extracting value of stringA there may chances when that particular value is removed from the hashmap at that time the null pointer error is thrown.
If you carefully debug your code in
if (alpha.containsKey(stringB.charAt(j))) {
Integer value = (Integer) alpha.get(stringA.charAt(j));
///Your code
}
Change it to
if (alpha.containsKey(stringB.charAt(j))) {
Integer value = (Integer) alpha.get(stringB.charAt(j));
///Your code
}
For your other question to make it case insensitive make both the string in lower case o upper case before beginning the operation
stringA = stringA.toLowerCase();
stringB = stringB.toLowerCase();
this is my first so I'll try to add as much info as possible so I don't get yelled at. :-)
What I am trying to do is I have 2 variables that grab text from 2 fields and take only the first character from each and assign it to those values.
This is the code that I use to get the strings. They are 2 separate calls as you would.
try { var_ContactSurname = var_ContactSurname.substring(0,1);
}
catch (Exception e){
}
I have the above again with a different variable. Now to this point it does what I want. It grabs the first letter from the fields and assigns it to the variables.
So at this point I have two variables (say with an example charater of D and R).
var_ContactSurname = R
var_ContactLicenceNumber = D
What I want to do is compare those two variables and if they match I want to return a value of TRUE, else FALSE if they don't match.
That value has to be a string as well and be assigned to a new variable called var_ContactValidate.
if (var_ContactLicenceNumber.toLowerCase().equals()var_ContactSurname.toLowerCase()){
var_ContactValidate == "TRUE";
}
else {
var_ContactValidate == "FALSE";
}
No you may notice that there might be some code missing. I am using a rules engine that does a lot of the functions for me. I can use raw Java code to do other things (like this compare)...but that's the compare that I am having a problem with.
Any ideas for that compare would be greatly appreciated.
Thanks.
i would use the String method equalsIgnoreCase()
to assign a value to a field, use a single =, not double (==).
if (var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname){
var_ContactValidate = "TRUE";
}
else {
var_ContactValidate = "FALSE";
}
check it
In addition to what already said - a simpler & more elegant version (without the if condition) could be:
var_ContactValidate = Boolean.toString(
var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname))
.toUpperCase();
Change your whole piece of code to:
if (var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname)){
var_ContactValidate == "TRUE";
}
else {
var_ContactValidate == "FALSE";
}
This combines the case insensitivity that you want, and passes through the second string as an argument of the .equalsIgnoreCase function.
Also, I am not sure what you are trying to do with the line:
var_ContactValidate == "TRUE";
If you want to assign var_ContactValidate to "TRUE" then use a single equals sign '=' as a double equals '==' compares the values instead. You may also considering using a boolean rather than a string in this case.
Here is an implementation that also checks for null values and empty Strings:
public class SurnameAndLicenseValidator {
public static void main(String[] args) {
// FALSE
validateSurnameAndLicense(null, "jb78hq");
validateSurnameAndLicense("Johnson", null);
validateSurnameAndLicense(null, null);
validateSurnameAndLicense("", "jb78hq");
validateSurnameAndLicense("Johnson", "");
validateSurnameAndLicense("", "");
validateSurnameAndLicense("johnson", "xb78hq");
// TRUE
validateSurnameAndLicense("Johnson", "jb78hq");
validateSurnameAndLicense("johnson", "jb78hq");
}
private static String validateSurnameAndLicense(String surname,
String license) {
String result;
if (surname != null
&& surname.length() > 0
&& license != null
&& license.length() > 0
&& Character.toUpperCase(surname.charAt(0)) == Character
.toUpperCase(license.charAt(0))) {
result = "TRUE";
} else {
result = "FALSE";
}
System.out.println(surname + " " + license + " " + result);
return result;
}
}
The main method is used as a unit test here. You might want to extract a real JUnit test from it, if you are into that kind of thing.
I trying to find whether the elements of 2 arrayLists are match or not.
But this code give me error Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException since some of the elements are null.
How can I solved this problem?
String level []={"High","High","High","High","High","High"};
ArrayList<Object> n = new ArrayList<Object>(Arrays.asList(level));
String choice []={null,"High","Low","High",null,"Medium"};
ArrayList<Object> m = new ArrayList<Object>(Arrays.asList(choice));
//Check if the two arrayList are identical
for(int i=0; i<m.size(); i++){
if(!(m.get(i).equals(n.get(i)))){
result= true;
break;
}
}
return result;
}
Just use Arrays.equals, like so:
String level []={"High","High","High","High","High","High"};
String choice []={null,"High","Low","High",null,"Medium"};
return Arrays.equals(level, choice);
The problem is that you are calling the equals method on some elements without first checking for null.
Change to:
for(int i=0; i<m.size(); i++){
if(m.get(i) != null && !(m.get(i).equals(n.get(i)))){
result = true;
break;
}
}
Or if you want to allow two null values to compare equal:
for(int i=0; i<m.size(); i++){
if (m.get(i) == null) {
if (n.get(i) != null) {
result = true;
}
} else if(!(m.get(i).equals(n.get(i)))){
result = true;
}
if (result) {
break;
}
}
One thing I don't get - why are you setting result to true when you find a mismatch? Don't you want to return true if both lists match and false otherwise?
The root of this problem could be you are using null as an actual value.
Just looking at your code you could use enum and instead of null use an EMPTY value. Then you can actually compare with in a list without nullpointerexceptions.
Check this out:
http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html
Also try to avoid using arrays. Just use List but use the proper type. Don't use List<Object> that is almost never valid.
null should indicate an error or testing only. It should never be used in valid code as you will create null pointer exception bugs during runtime.
if you know the first list never contains nulls switch the call around
if(!(n.get(i).equals(m.get(i)))){
also specifying ArrayList<Object> is bad practice, use List<String> if it is actually String objects.
Check if the objects are the same object (or both null) first. Check for null before you do the equals() test.
boolean result = true;
String level[] = { "High", "High", "High", "High", "High", "High" };
ArrayList<String> n = new ArrayList<String>(Arrays.asList(level));
String choice[] = { null, "High", "Low", "High", null, "Medium" };
ArrayList<String> m = new ArrayList<String>(Arrays.asList(choice));
// Check if the two arrayList are identical
for (int i = 0; i < m.size(); i++) {
String mElement = m.get(i);
String nElement = n.get(i);
if (mElement == nElement) {
result = true;
} else if ((mElement == null) || (nElement == null)) {
result = false;
break;
} else if (!(m.get(i).equals(n.get(i)))) {
result = false;
break;
}
}
return result;
}
Rewrite your if like this in order to check for both double-nullity and single-nullity:
if((m.get(i) == null && n.get(i) == null) || (m.get(i) != null && !(m.get(i).equals(n.get(i)))))
Rather than solving this specific problem, give yourself a tool you can use over and again, e.g.:
public static final boolean areEqual(Object o1, Object o2) {
return o1 == null ? o2 == null : o1.equals(o2);
}
...in some handy utility class, then use that in your loop.
But of course, for this specific requirement, derivation has the right answer (use java.util.Arrays.equals(Object[],Object[])).
Remove NULLs
You can remove NULL values from your List objects before processing.
myList.removeAll( Collections.singleton( null ) );
The Collections class is a bunch of convenient utility methods. Not to be confused with Collection (singular), the interface that parents List and is implemented by ArrayList.
See this posting, Removing all nulls from a List in Java, for more discussion.