It’s Michael, and today’s post will be about enums in Java. What exactly are enums?
Enums are special “classes” (that aren’t really classes in the Java sense) that represent groups of constants, such as unchangeable variables (which are any variables with the word final, as in public final int speed = 7). Remember that any final variables have set their values at the beginning of the class, rather than setting their values somewhere in the main code of the class. Also, you can’t change the values of final variables at any point in the main code.
Enums can be any list of strings or numbers, as you will see in the next example.
Enum is short for enumeration, which means “specifically listed”. It might be helpful to think of enums as lists of elements (but don’t confuse them with Arrays or ArrayLists)
So how do we create an enum? Take a look below:
public class Enums
{
enum Cats
{
Persian,
Bengal,
Sphinx,
Ragamuffin,
Calico
}
}
In this example, I created an enum that contains the names of five different cat breeds. To create an enum, remember to use the enum keyword instead of class, and remember to capitalize the first letter of each constant (if your enum contains words).
OK, the enum is great, but it can’t be run on it’s own. You’ll need a class with a main method, like this:
public class Enums
{
enum Cats
{
Persian,
Bengal,
Sphinx,
Ragamuffin,
Calico
}
In this example, I have incorporated the enum into the main class Enums (yes I know I could’ve picked a better name). In the main method, I am printing out an element from the enum.
But how did the main method return Sphinx as the output? Take a look at the line Cats myVar = Cats.Sphinx. This line tells Java to access the Sphinx element from Cats and store it in myVar (which is then printed out in the next line).
To access an element from an enum, remember to use the syntax Enum name.Enum element (and you should ideally store the accessed element in a variable of type Enum name (meaning the variable type should be the enum name).
You can also use an enum in a switch statement, like this:
public class Enums
{
enum Cats
{
Persian,
Bengal,
Sphinx,
Ragamuffin,
Calico
}
public static void main(String[] args)
{
Cats myVar = Cats.Calico;
switch(myVar)
{
case Persian:
System.out.println(“Persian cat”);
break;
case Bengal:
System.out.println(“Bengal cat”);
break;
case Sphinx:
System.out.println(“Sphinx cat”);
break;
case Ragamuffin:
System.out.println(“Ragamuffin cat”);
break;
case Calico:
System.out.println(“Calico cat”);
break;
}
}
}
In this example, I used a switch statement to display a certain output based on the value of myVar (the value of myVar was created using the Enum name.Enum element formula that I just discussed). Since the enum element I chose was Calico, the output displayed was Calico cat.
You can also loop through enums with a handy little method that is exclusive for enums. Here’s how to do so:
public class Enums
{
enum Cats
{
Persian,
Bengal,
Sphinx,
Ragamuffin,
Calico
}
public static void main(String[] args)
{
for (Cats myVar: Cats.values())
System.out.println(myVar);
}
}
The handy little enum-exclusive method that I was talking about is the values method, which returns an array of all of the elements in the enum. The values method is the best way to loop through all of the elements in an enum-plus, I don’t think for loops, while loops, or do-while loops would work for iterating through enums.
The syntax for an enum loop looks quite similar to the syntax of a for-each loop.
So, you might still be wondering “What are the differences between an enum and a class?” Here are two significant differences:
Enums can have attributes and methods, just like classes can. However, the elements of enums are unchangeable and can’t be overridden at any point in the code.
Enums can’t create objects, nor can they extend other classes (so a line like enum extends [class name here] won’t work)
You might also be wondering when the best times to use enums would be. The answer to that would be that the best times to use enums would be when you have values that you know won’t change. Let’s say you’re building a poker program-the values of the 52 cards won’t change, so those card values could be your enum. Another example would be if you were building a calendar program-the months of the year could be an enum, since each year will always have the same 12 months.
Michael here, and today I’ll post a Java lesson-my first one in nearly six months! Today’s lesson will be on ArrayLists in Java. What exactly is an ArrayList? Well, here’s an example:
package lesson14;
import java.util.ArrayList;
public class ArrayListsDemo
{
public static void main (String[] args)
{
ArrayList<String> cities = new ArrayList<String>();
}
}
An ArrayList is basically a resizable array. See, in Java, you can’t add/remove elements from an array without creating a new array (which interestingly isn’t the case with Python arrays), but with ArrayLists, you can add and remove elements as you wish. The other differences between arrays and ArrayLists include:
You need to import a package for ArrayLists, but not for arrays.
The syntax for ArrayLists is different than that for arrays. Here’s the basic structure for ArrayLists:
ArrayList<type> name_of_array = new ArrayList <type>()
All elements in an ArrayList must be of the same type!
In the example above, the ArrayList is empty. Let’s see how we can fill it up:
package lesson14;
import java.util.ArrayList;
public class ArrayListsDemo
{
public static void main (String[] args)
{
ArrayList<String> cities = new ArrayList<String>();
cities.add(“Nashville”);
cities.add(“Franklin”);
cities.add(“Chattanooga”);
cities.add(“Knoxville”);
cities.add(“Memphis”);
cities.add(“Murfreesboro”);
cities.add(“Brentwood”);
System.out.println(cities);
}
}
In this example, I used the add method to add the names of Tennessee cities into the cities ArrayList. Unfortunately, there isn’t a way to add several elements into the ArrayList with just one line of code; you’ll need to add all of the elements 1-by-1.
Now that we have elements in our ArrayList, let’s see how we can access them:
I would use the get method to access items in the cities ArrayList. The same element accessing array logic applies to ArrayLists, meaning that the first element corresponds to index 0, the second to index 1, and so forth. If you’re wondering why you see the entire ArrayList again, that’s because I appended the line System.out.println(cities.get(2)) to the end of the code that was present.
OK, so what if we want to change an element? Well, here’s the line of code to do that (along with the resulting output):
To change an element to an ArrayList, simply use the set method and include the index of the element you wish to change as well as the new value for that index as parameters. In this example, I am changing the element at index 5 (the 6th element) to Pigeon Forge.
To remove an element from an ArrayList, use the remove method along with the index of the element you want to remove as a parameter. In this example, I removed the element at index 3 (the 4th element).
If you wanted to empty the entire ArrayList, use the clear method.
Now let’s see how we can find the size of the ArrayList (after removing the element at index 3):
System.out.println(cities.size());
6
To find the size of the ArrayList, use the size method. In this example, the size of the cities ArrayList is 6.
Ok, so let’s see how we can loop through an ArrayList:
for (int i = 0; i < cities.size(); i++)
{
System.out.println(cities.get(i));
}
The best way to iterate through an ArrayList is with a for loop. Now, you could possibly try to iterate through an ArrayList with a while or do-while loop, but I’d stick with a for loop.
You should also use the size method to indicate how many times the loop should run.
You could also use a for-each loop to iterate through the ArrayList. Here’s how you’d write it:
for (String i: cities)
{
System.out.println(i);
}
Last but not least, I want to show you guys a cool little trick for ArrayLists that you can’t use for regular arrays. But first, you’d have to import the Collections class. Let me demonstrate:
import java.util.Collections;
Collections.sort(cities);
for (String i: cities)
{
System.out.println(i);
}
To sort the items in an ArrayList, first import java.util.Collections. To sort the elements, use the line Collections.sort(name of ArrayList) along with a for loop (or for-each loop, which I used here). You must loop through the ArrayList after sorting it, otherwise the sorting won’t work.
ArrayLists can either be sorted numerically or alphabetically (depending on the elements in your ArrayList). From what I tried, it seems like the Collections.sort method can only sort either in ascending order (for numerical ArrayLists) or alphabetical order (for non-numerical ArrayLists). I’m not sure if ArrayLists can be sorted in descending numerical order or reverse alphabetical order, but then again there could be methods for accomplishing these types of sorts.
It’s Michael, and today I thought I’d do an R lesson (which I haven’t done in almost 9 months). Today’s R lesson will be a little different, as it’s not an analysis. Rather, it’s a demo that shows what R can do beyond performing analyses-in today’s post, I’ll show you how to work with dates and times in R, as well as manipulate them with a handy little package called lubridate.
After installing the lubridate package, let’s start to play around with it. First, let’s create a date in three different formats:
In this example, I displayed a date in three different formats (year-month-day, month-day-year, day-month-year). Notice how the different date formats use different separators. For instance, the year-month-day format doesn’t use separators while the month-day-year format uses dashes and the day-month-year format uses backslashes.
Keep in mind these separators aren’t necessary, and if you use other separators for certain formats (or no separators at all), that would be perfectly acceptable. Just don’t incorrectly place certain elements of the date (in other words, don’t place the year first if you’re using month-day-year formatting).
Ok, so creating dates is only the basics of what the lubridate package can do-and we haven’t even gotten to the fun parts yet. For instance, did you know you could include a time with your date?:
In this example, I created the variable dateandtime, which contains today’s date (April 26, 2020) along with the time (12:10) using the mdy_hm function, which allows me to include the date (in month-day-year format) along with the time (only the hour and minute though).
You can also add an s to the mdy_hm function if you want to include seconds in the date-time object.
The time only works with 24-hour notation (more commonly known as “military time”), so trying to write something like “01:15 PM” wouldn’t work-unless you could figure out how to concatenate the “AM” or “PM” onto the end of the date-time object.
You could also change the formatting of the date in the date-time object, but remember to write the function according to the formatting you chose. For instance, if you chose to use year-month-day formatting, remember to write the function as ymd_hm (or ymd_hms if you choose to include the seconds)
But wait, there more you can include in a date-time object! Yes, you can also include the time-zone in your date-time object. See, the date-time object defaults to UTC, or Coordinated Universal Time. For those that don’t know what Coordinated Universal Time is, it’s not a time zone, but rather a 24-hour time standard used to synchronize world clocks. In other words, it’s the base point for all other time zones in the world, as they are determined by their distance from the UTC. Also, keep in mind that while the UTC doesn’t adjust to daylight savings time clock changes, the difference between the UTC and the local time does change. For instance, the difference between the UTC and US Central Time Zone is 6 hours when daylight savings time isn’t in place (from the first Sunday in November to the second Sunday in March), but only 5 hours when daylight savings time is in place.
So, let’s see what happens when we add the time-zone to our date-time object:
In this example, I added the US Central Time Zone to the date-time object (I chose Central Time since I am currently in Nashville, TN, which is in the Central Time Zone). The way to add the time-zone to a date-time object is to use the variable tz and set tz to US/(choose time zone). You can’t write the name of a city and expect R to recognize it (I know, since I tried to write US/Nashville and got an error from R).
I’m impressed that R knew the US is in Daylight Savings Time since the date-time object did have CDT (Central Daylight Time, as opposed to Central Standard Time) besides it. Then again, R probably looked at the date and time-zone and correctly assumed that the US is in Daylight Savings Time.
The next thing I want to show you is how to extract certain information in a date-time object. Here’s an example of that (using out dateandtime2 object):
All in all, there are 10 functions to extract information from a date-time object. Here’s an explanation of each of them:
second-extracts the second from the date-time object. In this example, second is zero since I didn’t include any seconds in this date-time object.
minute-extracts the minute from the date-time object. In this example, minute is 5 since the time in dateandtime2 is 13:05
hour-extracts the hour from the date-time object. In this example, hour is 13.
day-extracts the day from the date-time object. Since the date I used is April 26, 2020, 26 is given as the day
wday-extracts the number of the weekday from the date-time object. Since lubridate assumes the week starts on Sunday (some calendars start the week on Monday), Sunday is wday 1, Monday is wday 2, and so on until you get to Saturday (wday 7).
yday-extracts what day of the year the date is. In simpler terms, April 26, 2020 is the 117th day of 2020, so 117 is displayed.
week-extracts what week of the year the date falls on. Since April 26, 2020 is the 17th week of 2020, 17 is be displayed.
month-extracts the numerical value of the month, which can range from 1 (January) to 12 (December). Since April is the 4th month of the year, 4 is displayed
year-extracts the year from the date, which is 2020 in this case
tz-extracts the timezone from the date-time object (provided you set a timezone). In this case, the tz is US/Central, which is the US’s Central Time Zone.
Next, Iet’s demonstrate how to convert a date-time object into a different time zone:
This date-time object contains the date 05-02-2020 and the time 15:50 (which means 3:50PM). The tz is set to US/Central, which represents the US’s Central Time Zone (and my current city of Nashville, TN is in the Central Time Zone).
But what if I wanted to call some relatives in Bogota, Colombia? What time would it be there? Well, the with_tz function can help with figuring out this question. Simply use you date-time object and the timezone you wish to convert to as the parameters for this function. When I tried to find out the time in Bogota, Colombia, it turns out that when it’s 3:50PM in Nashville, TN, it’s also 3:50PM in Bogota, Colombia. The -05 means it’s five hours behind UTC (likewise, a +05 would mean that it’s five hours ahead of UTC).
Now, if it’s 3:50PM in Nashville, TN, what time would it be in Paris, France? Using the with_tz function, we can see that it’s 10:50PM in Paris, France, meaning that Paris is 7 hours ahead of Nashville. The CEST stands for Central European Summer Time.
But how would you know which timezone to use? Here’s a nice little hack-type in OlsonNames() into the compiler and you will see the list of all possible time-zones that lubridate will accept:
Last but not least, let’s learn how to do arithmetic with dates and times (and quite personally, I think this is tons of fun):
The lubridate packages contains two general time span classes-durations and periods. To create a function for periods, simply use the plural form for the unit of time you wish to make a period from. To create a function for durations, use the formatting for periods functions, but add a d in front of the unit of time.
In the hours() function, the amount of hours, minutes and seconds are displayed; since I used 15 for hours, the period is shown as 15H 0M 0S. In the dhours() function, the amount of hours are converted into seconds; since I also used 15 for hours, the duration shown is 54000s.
What if we used decimals for our period and duration functions? Let’s see what would happen:
In this example, I used 15.5 hours for both my period and duration functions. While 15.5 worked fine with my duration function, it gave me an error when I tried to use it with my period function because the parameter for a period function must be an integer.
The period function will give you the entire time period down to the second, while the duration function will always give you the length of the time period in seconds.
I’m not sure how far the duration function would go, but I did try using dmonth and got an error.
Why are there two classes of time in lubridate? This is because the calendar timeline isn’t as reliable as the number line. See, durations always supply mathematically precise results-a duration year is ALWAYS 365 days (even for a leap year like 2020). However, periods fluctuate the way the calendar timeline does, so in periods, 2019 has 365 days while 2020 has 366 days.
But, before I get into any further time-date arithmetic, let’s see how R can detect a leap year:
To find out whether a year is a leap year, simply use the leap_year() function along with the year you want to inquire about as the parameter. If the result is FALSE, the year isn’t a leap year, but if it’s TRUE, then the year is a leap year. As you can see, 2018 and 2019 aren’t leap years, but 2020 is a leap year.
Now, let’s perform some basic addition with period years and duration years:
When I add 1 period year and 1 duration year to the date January 1 2019, I get January 1 2020 both times. This is because 2019 has 365 days, so 1 period year and 1 duration year from January 1 2019 would add up to January 1 2020.
However, with a leap year like 2020, the results from period years and duration years would be different. Similar to the last example, I am adding 1 period year and 1 duration year to January 1 2020. Since period years fluctuate with the calendar timeline, 1 period year from January 1 2020 is January 1 2021. However, 1 duration year from January 1 2020 is December 1 2020, since duration years always contain 365 days (and 2020 has 366 days).
Aside from adding period years and duration years, you can also perform other arithmetic with other units of time (such as days and months);
In the first expression shown, I added 1 month to the date May 3 2020 and got June 3 2020. In the second expression, I subtracted 18 days from May 3 2020 and got April 15 2020.
Now, here’s where things get interesting. Notice how the third and fourth expressions shown generated error messages. This is because, unlike with regular numbers and decimals, you can’t multiply or divide units of time.
If you can’t multiply or divide units of time, then you certainly can’t do more advanced things like raising a date to a certain power or find the base-10 logarithm of a certain date (just saying in case anyone was wondering).
Now, there’s something interesting I wanted to point out when it comes to adding months to dates. In the example, when I added 1 month to May 3 2020, I got June 3 2020. Seems clear enough, right? Well, not always. See, there are two possible answers to adding a month to May 3 2020. They are:
June 3 2020, which is 31 days after May 3 2020
May 31 2020, which is 4 weeks after May 3 2020 (four weeks is considered a month)
I’ll explain the whole month addition thing later, but now, let’s discuss how to calculate the duration between two dates. To do this, we must first create a date interval:
To create an interval, use the interval function that lubridate provides. For the parameters, use two dates-and keep the second date greater than the first date.
You can also include date-time objects as parameters in interval, complete with time-zones. I just chose not to include them for simplicity’s sake.
I’m going to use my most recent holiday vacation for this example, which lasted from December 24 2019 to January 5 2020. I stored my interval in the variable vacation.
Now, how long was my holiday vacation in days?:
Dividing the vacation variable by ddays(1) gives us the length of my vacation in days-12. To be sure we get the exact duration in days, I had to use 1 as the parameter for ddays, because if I had used another number, I wouldn’t have gotten the exact duration. For instance, I tried vacation/ddays(2), and got 6, which is half the duration of my vacation (in days).
I could’ve used days(1) instead of ddays(1) and I would’ve gotten the same answer-12.
Now here’s another example of an interval:
This interval represents how long I’ve been living in Nashville as of May 3 2020. 09052019 is the first parameter, since I moved to Nashville on September 5 2019.
Now how long is that in days and months?:
So, according to these calculations, I’ve been living in Nashville for 241 days, or 7.93 months as of May 3 2020. What I find interesting is that the days and ddays functions both returned 241, despite having a February 29 factored in.
Now let’s try an even larger time interval:
This interval represents how long this blog has been active for as of May 3 2020 (I launched this blog on June 13 2018). So how long would this be in years, months, and days?:
All in all, this blog has been active for:
1.888 period years and 1.89 duration years.
22.67 months
690 days (both period days and duration days)
Personally, I think it’s interesting that dyears and ddays can be used, but not dmonths. But I guess it’s just one of those R quirks.
Last but not least, let’s discuss the whole adding months thing. Earlier in this post, I did mention there were several possible answers to adding a month (or months) to a certain time using the example of May 3 2020. In that example, I said that there were two possible answers to the question of adding a month-June 3 (31 days from May 3) or May 31 (four weeks from May 3). See, since the 12 months of the year aren’t equal length, trying to do arithmetic with them won’t work.
So, how would we approach this problem? Let’s take a look:
In this example, the months function keeps adding a month to 04302020 (April 30 2020) 11 times. You can see the results of the months function in the output below; the first result is 2020-04-30 and the last result is 2021-03-30, which is 11 months from the start date.
But wait, what’s the NA doing there? See, since there’s no such date as February 30 2021, an NA is displayed in its place.
The syntax for the months functions is as follows-months(X months from date:Y months from X). This means that the value to the left of the colon should be how many months from the start date you want to begin the calculation at and the value to the right of the colon should be how many months from the first value you want the calculations to end at.
It’s not necessary to use 0 as the first value for the months function, but if you want to include the given date in your calculation, then use 0.
OK, so what if we didn’t want to see any NA values. Here’s how we’d approach that:
The floor_date function automatically starts the calculations on the first of the month following the date given (since I gave 05032020 as the date, the calculations automatically start with June 1 2020). The months function will add 1 month to June 1 2020 11 times and display all 12 of these results (the 12 results include June 1 2020). The days function tells R to run under the assumption that each month has 31 days (though using 28 for days would’ve worked just fine too).
OK, so there’s another approach to the whole adding-a-month-to-a-date-several-times question. Here it is:
Using the %m+% and %m-% operators, you can get a list of months up to X months out from a certain date. The amazing thing about these operators is that they will automatically roll back to the last day of the month if necessary.
One thing to keep in mind is that the %m+% operator will move forward 1 month for X amount of months but the %m-% operator will move backwards 1 month for X amount of months. At least both are very precise when calculating months.