public static void main(String[] args) {
Map<String, HashSet<String>> test = new HashMap<String, HashSet<String>>();
test.put("1", new HashSet<String>());
System.out.println(test);
System.out.println(test.get("1"));
if(test.get("1") == null){
System.out.println("Hello world");
}
}
The first println gets me {1=[]}
The second one gets me []
I am trying to print out "Hello world" but the if statement isn't going through.
Is the empty HashSet, [] not equal to null?
How do I use the empty HashSet in this if statement?
There is a difference between null, which means "nothing at all," and an empty HashSet. An empty HashSet is an actual HashSet, but one that just coincidentally happens to not have any elements in it. This is similar to how null is not the same as the empty string "", which is a string that has no characters in it.
To check if the HashSet is empty, use the isEmpty method:
if(test.get("1").isEmpty()){
System.out.println("Hello world");
}
Hope this helps!
Is the empty HashSet, [] not equal to null?
Correct, it is not. This is precisely the reason your code behaves the way it does.
To check for both null and empty set, use the following construct:
HashSet<String> set = test.get("1");
if (set == null || set.isEmpty()) {
...
}
The empty HashSet isn't a null. Add a test by using the HashSet.size()
if (test.get("1") == null || test.get("1").size() == 0) {
or use HashSet.isEmpty(),
if (test.get("1") == null || test.get("1").isEmpty()) {
Alternatively, you could comment out
// test.put("1", new HashSet<String>());
System.out.println(test);
Then test.get("1") is null.
You should use the Set_Obj.isEmpty() method. This returns a boolean value checking if the set has any element in it (true).
Related
I know the isEmpty() method used to check if an arraylist is empty, but I am trying to check if an arraylist is not empty. I tried to look online but I didn't find any useful information on how to do this. My code is like "while ArrayList is not empty then run code).
Invert the result of isEmpty().
public boolean notEmpty(ArrayList a) {
return !a.isEmpty();
}
That will tell you when a list is not empty.
Alternatively, you can also check whether the array is null by the length/size of the arraylist.
while(arrayListName.size() > 0 ){
//execute code
}
If you initialize arrays as null you can just check if they are not null:
List<String> myArray = null;
myArray = myFunction.getArrayValues;
if (myArray != null) {
processArray (myArray);
}
This is easier to read for me
while (arrayList.isEmpty() == false) {
//do something cool
}
Can be useful
if (!arrayList.isEmpty() ){
//execute code
System.out.println(arrayList.get(arrayList.size()-1));
}
I have a doubt regarding checking null condition.For eg :
if(some conditon)
value1= value; //value1 is string type
else
value1= "";
Similarly some 4 other string value has similar condition.
What i need is i want to check whether all those 5 string value is null or not,Inorder to do some other specific part.
i did it like this
if(value1 == null)
{
}
but the pgm control didnot entered the loop eventhough value1="".
then i tried
if(value1 ==""){
}
this also didnt worked.
Cant we check null and "" value as same??
can anyone help me??
If you want to check is a String is null, you use
if (s == null)
If you want to check if a string is the empty string, you use
if (s.equals(""))
or
if (s.length() == 0)
or
if (s.isEmpty())
An empty string is an empty string. It's not null. And == must never be used to compare string contents. == tests if two variables refere to the same object instance. Not if they contain the same characters.
To check both "is not null" and "is not empty" on a String, use the static
TextUtils.isEmpty(stringVariableToTest)
It looks like you want to check wether a String is empty or not.
if (string.isEmpty())
You can't check that by doing if (string == "") because you are comparing the String objects. They are never the same, because you have two different objects. To compare strings, use string.equals().
When you are working on String always use .equals.
equals() function is a method of Object class which should be overridden by programmer.
If you want to check the string is null then if (string.isEmpty()) else you can also try if (string.equals(null))
You can use:
we can check if a string is empty in 2 ways:
if(s != null && s.length() == 0)
if(("").equals(s))
prefer below.
String str;
if(str.length() > 0)
{
Log.d("log","str is not empty");
}
else
{
Log.d("log","str is empty");
}
I have an application which requires to check if a String is present in an array of String type, before adding it so as to avoid duplication. To do this, I wrote the following function:
public boolean arrayHas(String[] arr, String str)
{
for(int i=0;i<arr.length;i++)
{
if(arr[i].equals(str))
return true;
}
return false;
}
To invoke this function, I'm using:
if(!arrayHas(contacts,str))
{
contacts[i] = str;
i++;
}
contacts and str are declared as follows
public static String contacts[] = new String[]{};
String str = "";
Bundle bun = getIntent().getExtras();
str = bun.getString("key");
Elements are added to 'contacts' only through the main code, it is empty at the beginning. I tried adding a toast to display the value of 'str' received through the intent and it works fine. But I'm getting a NullPointerException in the 'if' statement in the arrayHas function. Could someone help me out?
Seems that you haven't initialized the array with elements. So all of them are NULL.
In you arrayHas function check if the element you are comparing with is a null or not.
if(arr[i] != null && arr[i].equals(str) )
{
// do your operation
}
Also before calling arrayHas function in
if(arrayHas(contacts,str)) { }
put a check if contacts is null or not.
Two issues:
First: add a null check in if as:
if(arr[i] != null && arr[i].equals(str))
because that position may not have assigned with a valid string yet e.g. in the very beginning, no assignment is made and arr[0] is null so comparison will result into NullPointerException.
Second: I think you want to check the not ie. ! condition in this check:
if(!arrayHas(contacts,str))
{
contacts[i] = str;
i++;
}
If you want to avoid duplication, use a java.util.Set<String>, it will take care of it for you. You can always uso toArray() if you really need an array later on.
If you care about the order of your elements, you can also use a java.util.List, and check the presence of the element with list.contains(str)
Use this instead :
String contacts[] = new String[10];
String str = "somethiung";
if(Arrays.asList(contacts).contains(str))
{
contacts[i] = str;
i++;
}
Arrays.asList(.).contains(.) gives you a much better way to test if a string is present in an array.
By the way make sure that contacts and str are properly initialized.
Just a suggestion to code style. Try to defensive programming., ie. you are checking whether the string str is present in arr in that case always do the check in reverse ie., str.equals(arr[i]), so that unnecessary NPEs wont be raised.
In this case an NPE could be raised at 2 points, if arr is null .length and .equals will throw NPE's. From this its evident that, either arr is null , or arr[i] is null.
Find the method where arr is filled with data, there something is going wrong.
thanks
You must not have initialized your contacts[] but it might be the case like str[0]=null but str[1]="something";
in that case change
arr[i].equals(str) to `str.equals(arr[i])` as str is less likely to be null
- I think you are trying to find whether a String is a present in the Array of Not.
- First use Collections cause that will be much more flexible in comparision to Array.
- Use Collections.contains() method to find the String if present of not.
For example if you are using List:
List<String> list = new ArrayList<String>();
list.contains("string_to_be_found");
I want check whether a String value val is contained within a List of Strings lets call it stringList.
I am doing this
if(stringList.contains(val)){
System.out.println("The value is in there");
}
else{
System.out.println("There's no such value here");
}
But it always seems to be that the value is not included. Is this because two String values that have the same characters are not actually equal? For a "home-made" class I could implement hashCode() and equals() and fix this, what can I do for String data?
EDIT:
The way I am getting val is outlined here:
List<String> stringList = new ArrayList<String>();
stringList.add("PDT");
stringList.add("LDT");
stringList.add("ELNE");
String myFile = "/folder/myFile";
InputStream input = new FileInputStream(myFile);
CSVReader reader = new CSVReader(new InputStreamReader(input), ',','"', 1);
String[] nextLine;
try {
while ((nextLine = reader.readNext()) != null) {
if (nextLine != null) {
if (nextLine[6] != null){
String val = nextLine[6];
if(stringList.contains(val)){
System.out.println("Success");
}
}
}
}
ArrayList.contains() uses Object.equals() to check for equality (hashCode() is not involved in List). This works well for strings. Probably, your string really isn't contained in the list...
You've probably overlooked some whitespace or upper/lower-case or encoding difference...
More code please!
This works:
import java.util.*;
public class Contains {
public static void main(String[] args) {
List<String> stringList = new ArrayList<String>();
stringList.add("someString");
String val = new String("someString");
if (stringList.contains(val)) {
System.out.println("The value is in there");
} else {
System.out.println("There's no such value here");
}
}
}
That doesn’t sound right: contains uses equals rather than ==, so if the string is in the list, it should be found. This can be verified in the indexOf method of the superclass AbstractList used by ArrayList.
Following your edit, make sure you trim strings before doing contains, as otherwise they may contain the newline character(s).
Try the following, first make the check more concrete by iterating the list and checking each element separately. Than, when you hit the elements that you are expecting to be equal, This is what you are supposed to be looking at. Check to see if they are really equal. Maybe there is a case difference? (or some other elusive but plain difference like white space?)
Try to override equals(){}, so that you can specify which property needs to compare equality .... :P
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.