Utilities in Java

Utilities

There is a set of utilities within the Java language

Found in the package java.util

These are useful and everyday classes, among which we highlight:

  • Collections
    • Collection
      • List
      • Set
      • Map
  • Dates
    • Date
    • Calendar
  • Properties
  • Scanner

Collection

The API of collections of Java includes classes that are able to hold sets of objects

Represent containers of objects

They are dynamic structures, grow as elements are added and work with Objects

  • You can add any thing

  • To retrieve the item must be done casting

There are basically two sets:

  • Classes that implement Collection

    • Represent containers of objects

    • There are basically lists (List) and sets (Set)

  • Classes that implement Map

Some of its most important methods are:

  • boolean add(Object o)

    adds an item to the collection

  • boolean addAll(Collection c)

    adds a group of objects (another collection) to the collection

  • void clear()

    empty the collection

  • boolean contains(Object o)

    checks if an element is within the collection

  • boolean isEmpty()

    checks if the collection is empty

  • Iterator iterator()

    returns a java.util.Iterator to iterate through the elements of the collection

  • boolean remove(Object o)

    removes an item from the collection

  • int size()

    number of objects stored

  • Object[] toArray(Object[] a)

    returns an array with the elements of the collection

List

Serves as the interface for classes that represent data lists or dynamic arrays

Its elements are accessible by means of an index

Inherits the methods of Collection and also adds:

  • void add(int index, Object element)

    adds an element at a given position

  • Object get(int index)

    returns the item that occupies a certain position

  • int indexOf(Object o)

    returns the index of the first occurrence of the item in the list (or -1 if it cannot be found)

  • Object remove(int index)

    it removes the element that occupies a certain position

  • Object set(int index, Object element)

    changes the element that occupies a particular position with another element

When you add an object with add(Object), the element is added at the end

When you delete an object with remove(Object), everyone else moves so as not to leave gaps

The objects List most common are Vector (is threadsafe) and ArrayList (not threadsafe)

Set

Serves as an interface for classes that represent datasets

Can not have duplicate elements

Its elements are not accessible by an index

Adds No new methods

The objects Set most common are HashSet and TreeSet

Map

Represent tables of data

The whole map consists of a set of entries composed of:

  • A key, it serves to retrieve the item
  • A value

The most important methods are:

  • void clear()

    empty the structure

  • boolean containsKey(Object key)

    returns true if there is any object stored with that key

  • boolean containsKey(Object value)

    returns true if the Map contains that object

  • Object get(Object key)

    allows you to retrieve a specific item from its key

  • boolean isEmpty()

    indicates if the Map is empty

  • Set keySet()

    returns a set of keys in the Map

  • Object put(Object key, Object value)

    stores an object on the map with a particular class. If the key is already stored it is replaced by an associated object with the new

  • void putAll(Map t)

    includes a submap on the map

  • Object remove(Object key)

    deletes an object from given key

  • int size()

    returns the number of objects stored

  • Collection values()

    returns the set of values stored in the map

Are implemented as Hash tables

The most common are HashMap (not threadsafe) and Hashtable (is threadsafe)

Iterator

There are collections that are accessed through an index, others not

Iterator lets you iterate over collections of objects regardless of how they are organized

Otra ventaja, permite eliminar objetos sin tener que gestionar los indices

The most important methods are:

  • boolean hasNext()

    returns True if the iterator has any more element

  • Object next()

    returns the next element of the iteration

  • void remove()

    removes from the collection the last element returned by the iterator

Comparison of route of a Collection
for with index
Iterator

Dates

There are two classes that allow you to work with dates:

  • Date

    almost all of its methods are deprecated so it is not recommended to use

  • Calendar

    it is an interface which is very easy to give you the behavior you want

Both of the internally represented time by a value of type long that represents the number of milliseconds from the January 1, 1970 at 00:00:00 GMT

That value can be obtained using System.currentTimeMillis()

Calendar allows for many more operations with dates Date, although it is more difficult build (being an interface we will have to do its implementation ourselves)

Date

It is easy to build:

  • new Date()

    constructs an object Date with the current system date

Methods that are not deprecated:

  • boolean after(Date when)

    checks to see if the date is later than the one supplied as a parameter

  • boolean before(Date when)

    checks to see if the date is previous to the one supplied as a parameter

  • long getTime()

    returns the number of milliseconds since the 1 de Enero de 1970 a las 00:00:00 GTM

  • void setTime(long time)

    changes the date to another date in milliseconds

Deprecated methods:

  • int getDay()

    returns the day of the week for that date or returns the day that represents that instant in the local area

    Day of the week
    Day Sunday Monday Tuesday Wednesday Thursday Friday Saturday
    Value 0 1 2 3 4 5 6
  • getMonth()

    returns the month for that date starting with 0

    Months
    Month January February March April May June July August September October November December
    Value 0 1 2 3 4 5 6 7 8 9 10 11
  • getYear()

    returns the year for that date that has been subtracted from 1900

  • getHours()

    returns the time for that date, which will be between 0 and 23

  • getMinutes()

    returns the minutes for that date, which will be between 0 and 59

  • getSeconds()

    returns seconds for that date, which will be between 0 and 61, values 60 and 61 will only appear when the MVJ skips for a few seconds in an account

Calendar

Abstract class for representing dates in different types of calendars

It includes a lot of constants for all days of the week, months, fields of a date...

In the west, to get the date of the system we will use the GregorianCalendar:

  • new GregorianCalendar()
  • new GregorianCalendar(2007, 1, 5)

    Attention should be paid to the date:

    • es año, mes, día

    • Corresponds to the February 5, 2007 and not the January 5, 2007 as it might seem at first glance

      January corresponds to the value 0

We can also get the system date by using the static method Calendar.getInstance()

The most noteworthy methods are:

  • void add(int field, int amount)

    adds (or subtracts, depending on the sign of the operand) time to a date

  • boolean after(Object when)

    checks to see if the date is later than the one supplied as a parameter

  • boolean before(Object when)

    checks to see if the date is previous to the one supplied as a parameter

  • int get(int field)

    returns the value of some field of the date, which we specify with the parameter field

  • Date getTime()

    converts the type Calendar to Date

  • void set(int field, int value)

    change of value of a date field

  • void set(int year, int month, int date)

    changes the year, month and day of the date

  • void setTime(Date date)

    from a Date, creates a Calendar

Properties

Usually the behavior of applications can change in function of parameters

It is very comfortable to place those settings in the files for the application to the lea as needed

Java has the class Properties that automates this management

Each line in the property file saves a variable and is formatted as:

We will use the file called connection.properties which will have the following content:

To show the use of Properties with the following example:

Scanner

You can use the class Scanner to read primitive types and Strings using regular expressions

The class Scanner collect the characters typed from the keyboard until you find a delimiter which by default is space

The collected data are converted to different types using the method next<type>(), to collect texts like String we will use only next()

In this way we will be able to collect from the keyboard or other means, the types of data that we need

In the example we have read a int from the keyboard

In the example we have read several long from a file called numbers.txt

In the example we read several words from a String

Showing us on screen:

That is, the words contained in the String, each on one line at a time because we used println to display them on the screen

As we can see, if instead, we would have used print the would have shown all on the same line without any delimiter between them

In the example we read several words from a String changing the delimiter space by the delimiter 1

To set the new delimiter we use the method useDelimiter and we pass it parameter a string containing a regular expression, in this case \\s*1\\s*

Showing on the screen the same as in the previous example, despite using a different delimiter