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));
}
Related
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).
I'm having ArrayList Contains of String. I would like to check whether the character is present in the arraylist. I'm using the following code.
if(list.toString.contains(char))
{
// enter code here
}
Can i use this toString() method. What is the drawback?
It would be a really bad idea to use List.toString() and search that. Your code should probably look something like this :
Iterator it = list.getIterator();
char searchChar = 'S';
while (it.hasNext())
{
String s = (String) it.next();
if ( s.contains(searchChar) )
{
//Found the char!
}
}
No you cannot go ahead with arraylist.toString(), as it will not provide string representation of contents in String.
Better approach is to iterate over list and check, as below.
for(String detail:listString){
if(detail.contains('X')) //replace 'X' with your character
{
// do somethng
}
}
Try this,
Arrays.toString(inputList.toArray()).contains(searchValue);
list.toString() gives you a string representation of a list and thus it contains more characters then just the concatenated list elements
[stringElement1, stringElement2, ... ]
Therefore your approach will not work if the character you are looking for is , , , [ or ].
And keep in mind that this string representation is implementation specific. It might not work for other list implementations than ArrayList
I would recommend to write a method linke this:
private boolean listElementContains(List<String> list, String subString){
for(String element : list){
if(element.contains(subString)){
return true;
}
}
return false;
}
You can call toString() on any Java Object. List is an Object which contains (you guessed it) a list of other Objects. Therefore, you can also call toString() on each Object contained within the List. You should read about inheritance in Java.
In your particular case, you have a List of Strings. What you actually want to do is check each String in the List to see if the String contains a particular character. Topics you may want to read about include iteration, for loops, and for each loops.
If I understand this correctly, your code would look like this:
List<String> strings = new ArrayList<>();
//add strings to list
for (String string : strings) {
//Look for some character c
if (string.indexOf(c) >= 0) {
return true;
}
}
return false;
On the matter of list.toString, that simply returns a representation of the object as a string; it has nothing to do with the contents. Think of it like a label on a box of stuff that says "Junk." The box is labeled Junk, but you have no idea what's in it.
What's nearly certain is that toString will return a nonsense label for the object in memory. So to get at what's inside, you need to loop through the contents as shown above.
if(list.toString.contains(char))
String's contains() method won't take char as param, instead check with indexOf
Your code works, with little modifications.
A small example here:
List<String> list= new ArrayList<>();
list.add("test");
list.add("test2");
if (list.toString().indexOf('t') > -1) // True
{
System.out.println("yes there");
}
Note:
As a workaround, Make an char array and add your char in to that array and then use contains method.
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 couldn't find anything on that while googling
so
I want to create an array only if it doesn't already exists.
EDIT: I mean not initialized
I know how to check for values in the array
Should be simple but I'm stuck
best regards
static long f(long n) {
int m = (int)n;
**if (serie == null) {
long[] serie = new long[40];
}**
if (n == 0) {
return 0;
}
else if (n==1) {
return 1;
}
else {
long asdf = f(n-1)- 2*(f(n-2)) + n;
return asdf;
}
}
something like that
a recursive function and I want to save the values in an array
You are trying to use the serie array but it is not yet declared. First declare it and then use it, as you want.
Are you looking for:
if (values == null)
{
values = new int[10];
}
or something like that? If not, please edit your question to provide more information.
EDIT: Okay, judging by the updated question, I suspect you ought to have two methods:
static long f(long n)
{
return f(n, new long[40]);
}
static long f(long n, long[] serie)
{
// Code as before, but when you recurse, pass in serie as well
}
(Note that your current code doesn't use serie at all.)
if(array==null){
//create new array
}
AFAIK, there are, if you use a variable in java, it is initialized. So you probably want to check if that variable, an array in this case, is null. Not only that, you can and probably should check if it is an array. Arrays are objects in java. So you could do something like this for an array:
if(!obj.getClass().isArray())
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.