Recursive functions in JAVA

Did you know that one of the most used programming languages, JAVA, doesn't have a list option? You can only create Array's with a set amount of elements.

So now still want to make a list in JAVA for something. Then you might get the idea to just make a really long array and use it instead of a list. You could do that, but keep in mind, that this array is going to take up some memory and with some, I mean lots of. This happens because would you use an array, you have to make sure this array is big enough to handle the longest list you can think of and then you still have to add some, because somebody is going to top even that limit.

Now, after you have made this beautiful list in JAVA (I wont explain in this post how you do this), you may want to find the elements in the list. This is where Recursive functions shine in JAVA.

Imagine this: You made a list of pies in JAVA, where every object in the list represents a different type of pie. Now you get step by step through every element of the list and search for the pie named apple-pie. This works because every object has the function search pie and it knows which pie is the next one. An example code could look like this:

PIE nextpie;

PIE searchpies(PIE searchedpie){
    if(this.pie == searchedpie){
        return this;
    }else{
        return nextpie.searchpies(searchedpie);
    }
}

You can see that by using this recursive function you can pretty easily search your entire list for a specific item.

This article was updated on October 27, 2024

Hey, I am David, the owner of this blog.
Feel free to have look around and read the articels I write.