How can I check if anything is in an ArrayList - java

So I want to check if anything exists in an array list in an if statement. So instead of
MyArrayList.Contains("blah");
I want something that checks if ANYTHING is in it.
EDIT!:
Found it out!
Thanks for all the help!
Answer:
MyArrayList.isEmpty(){
}
THANKS!

List.isEmpty() is what you are looking for. Refer the docs.

You should to check if your ArrayList is not empty.
You can get achieve this like this code snippet:
if (!arrayList.isEmpty()) {
//your code here...
}

Just check the size of the list. If it's not zero, then there is something in it...
if(arrayList.size() != 0) {
//there is something in the list
}

List.isEmpty():
if (! list.isEmpty()) {
// do something
}
List.size():
if (list.size() > 0) {
// do something
}
Also, keep in mind that most of the time it's preferable to program against the interface (in this case, List) rather than the concrete class (e.g., ArrayList, LinkedList)

You could do it simply like this using .isEmpty():
if(!myArrayList.isEmpty()){
//if your array list has something in it
}
and,
if(myArrayList.isEmpty()){
//if your array list has nothing in it
}

Related

is there way to select everything from a list of model?

asnafList is my list and getIc_number is my getter below is my code
asnafList.get(0).getIc_number();
I am trying to make sort of an authenticating feature for my apps and I use the above code in my if statement for the button. That code only get the 0 position of the list. So my question is, is there a way to get all of the position is the list to compare with the input from the user using the if statement?
int number;
for(int i = 0; i < asnafList.size(); i++) {
number = asnafList.get(i).getIc_number();
if(number == YOUR_COMPARABLE_NUMBER) {
// Compare and do anything here
}
}
As Kushal answered, a for loop is useful for this. But I usually use a for each loop in this scenario. Not sure what type of objects are in the asnafList, but it will look something like this:
for(AsnafObject a : asnafList) {
if(a.getIc_number() == YOUR_COMPARABLE_NUMBER) {
// do stuff
}
}
When you do this for loop, you basically iterate through every object in the asnafList, where AsnafObject is the classtype of your asnafList and a is the object which you can use to call any non-static methods of AsnafObject (or however your class is called)

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" );

how do i use a hashmap keys to an array of strings?

im currently working on a multiple class assignment where i have to add a course based on whether the prerequisites exist within the program.
im storing my courses within the program class using a hashmap. (thought i would come in handy) however, im having a bit of trouble ensuring that these preReqs exist.
here is some code ive currently got going
public boolean checkForCourseFeasiblity(AbstractCourse c) throws ProgramException
{
AbstractCourse[] tempArray = new AbstractCourse[0];
tempArray= courses.keySet().toArray(tempArray);
String[] preReqsArray = new String[1];
preReqsArray = c.getPreReqs();
//gets all course values and stores them in tempArray
for(int i = 0; i < preReqsArray.length; i++)
{
if(courses.containsKey(preReqsArray[i]))
{
continue;
}
else if (!courses.containsKey(preReqsArray[i]))
{
throw new ProgramException("preReqs do not exist"); //?
}
}
return true;
}
ok so basically, tempArray is storing all the keySets inside the courses hashmap and i need to compare all of them with the preReqs (which is an array of Strings). if the preReqs exist within the keyset then add the course, if they dont do not add the course. return true if the course adds otherwise through me an exception. keep in mind my keysets are Strings e.g. a keyset value could be "Programming1" and the required prerquisite for a course could be "programming1". if this is the case add then add the course as the prereq course exists in the keyset.
i believe my error to be when i initialize mypreReqsArray with c.getPreReqs (note: getPreReqs is a getter with a return type String[]).
it would be really great if someone could aid me with my dilemma. ive tried to provide as much as possible, i feel like ive been going around in circles for the past 3 hours :(
-Thank you.
Try something like this, you don't need tempArray. The "for each" loop looks lots nicer too. If you want to throw an Exception I would put that logic in the place that calls this method.
public boolean checkForCourseFeasiblity(AbstractCourse c)
{
for(String each : c.getPreReqs())
{
if(! courses.containsKey(each))
{
return false;
}
}
return true;
}

iterating an enum with a while loop

Sorry for the very noob question.
Let's suppose I have an enum like so
public enum MyElementType {
TYPE_ONE,
TYPE_TWO,
TYPE_THREE;
}
When I want to loop over this enum, I always see this solution:
for(MyElementType type: MyElementType.values())
{
//do things
}
I wonder if there exist a viable solution with the while loop.
Seraching around I see that Enumeration interface exposes the method
hasMoreElements()
but I don't know how to link the things together.
Any advice?
Why do you want to use a while loop rather than the for-each you more typically see?
In any case, it's pretty simple
Set<MyElementType> elements = EnumSet.allOf(MyElementType.class);
Iterator<MyElementType> it = elements.iterator();
while (it.hasNext()) {
MyElementType el = it.next();
// etc
}
// or
Iterator<MyElementType> it = Arrays.asList(MyElementType.values()).iterator();
Take a look # http://www.javaspecialists.eu/archive/Issue107.html

Code explanation

Given these set of instructons am I right in saying that :
1) Here I declare two list objects called : audiobytes and lines
List<Byte> audioBytes;
List<Line2D.Double> lines;
2) Here I empty the lists created in step 1 , and update the component --> repaint()
public void resetWaveform() {
audioBytes = new ArrayList<Byte>();
lines = new ArrayList<Line2D.Double>();
repaint();
}
3) Here unfortunately I don't understand:
public void createWaveForm() {
// what does it mean ????
if (audioBytes.size() == 0) {
return;
}
}
What puzzles me is that the method is called createWaveForm but actually does nothing..is
that correct?
1) Correct
2) Almost. I would create lists in #1 and then call clear() on each. Simply because dealing with nulls is a nightmare
3) It does nothing only when list of audio bytes has no data. I guess there is more code after the if statement
You did not empty the lists in step 2, you threw them away and created 2 new lists. This is not the same if something is still holding a reference to the old lists. You should use the clear() method instead.
As far as your code in part 3, yes it really does nothing (except needlessly check the size), assuming you haven't cut anything out. If there was something else there, then all that segment of code is saying is "if there is no data, return (don't execute anything more)".

Categories