7. Utility Classes

Lecture




  • Work with arrays
  • Local installations
  • Work with dates and time
    • Time zone and summer time
    • Сalendar class
    • Subclass of GregorianCalendar
    • Date and Time Representation
  • Getting random numbers
  • Copying arrays
  • Interaction with the system

This chapter describes the tools that are useful for creating programs: working with arrays, dates, random numbers.

Working with arrays

The Arrays class from the java.utii package contains many methods for working with arrays. They can be divided into four groups.

Eighteen static methods sort arrays with different types of numeric elements in ascending order of numbers or just objects in their natural order.

Eight of them have a simple look.

static void sort (type [] a)

where type can be one of the seven primitive types byte, short, int, long, char, float, double OR TYPE Object .

Eight methods with the same types sort the part of the array from the from index inclusive to the index to exclusively:

static void sort (type [] a, int from, int to)

The remaining two sorting methods order the array or its part with elements of type object according to the rule specified by the object with, implementing the interface   Comparator :

static void sort (Object [] a, Comparator c)

static void sort (Object [] a, int from, int to, Comparator c)

After sorting, you can organize a binary search in the array with one of nine static search methods. Eight methods are

static int binarySearch (type [] a, type element)

where type is one of the same eight types. The ninth search method is

static int binarySearch (Object [] a, Object element, Comparator c).

It looks for an element in an array sorted in the order specified by object c .

Search methods return the index of the found element of the array. If the element is not found, then a negative number is returned, meaning the index with which the element would be inserted into the array in the specified order, with the opposite sign.

Eighteen static methods fill an array or part of an array with the specified value :

static void fill (type [], type value)

static void fill (type [], int from, int to, type value)

where type is one of the eight primitive types or object type. Finally, nine static logic methods compare arrays:

static boolean equals (type [] al, type [] a2)

where type is one of eight primitive types or type Object .

Arrays are considered equal, and returns true if they have the same length and equal elements of arrays with the same indices.

Listing 7.1 shows a simple example of working with these methods.

Listing 7.1. Using Arrays Class Methods

import java.utii. *;

class ArraysTest {

public static void main (String [] args) {

int [] a = {34, -45, 12, 67, -24, 45, 36, -56};

Arrays.sort (a);

for (int i = 0; i <a.length; i ++)

System.out.print (a [i]. + "");

System.out.println ();

Arrays.fill (a, Arrays.binarySearch (a, 12), a.length, 0);

for (int i = 6; i <a.length; i ++)

System.out.print (a [i] + "");

System.out.println ();

}

}

Local installations

Some data — dates, times — are traditionally presented in different places in different ways. For example, the date in Russia is displayed in the format day, month, year through a dot: 27.06.01. In the USA, a month / date / year entry is accepted through the slash: 06/27/01.

The combination of such formats for a given locale, as they say in the jargon "locale", is stored in an object of the Locale class from the java.utii package. To create such an object, it is enough to know the language and the country. Sometimes a third characteristic is required - a variant variant that defines a software product, for example, "WIN", "MAC", "POSIX".

By default, local settings are determined by the operating system and read from system properties. Look at the lines (see fig. 6.2):

user.language = en // Language - Russian

user.region = RU // Locality - Russia

file.encoding = Cpl251 // Byte-Coding - CP1251

They define the Russian locale and local encoding of byte characters. The default locale on the machine where the program is running can be determined by the static method Locale.getoefauito .

To work with another locale, it must first be created. For this, the Locale class has two constructors:

Locale (String language, String country)

Locale (String language, String country. String variant)

The language parameter is a string of two lowercase letters defined by the ISO639 standard, for example, "ru", "fr", "en". The country parameter is a string of two uppercase letters defined by the ISO3166 standard, for example, "RU", "us", "ev" . The variant parameter is not defined by the standard, it may be

for example, the string " Traditional ".

Locale is often indicated with one line "ru_RU", "en_GB", "en_us", "en_CA ", etc.

After creating a locale, you can make it the default locale by the static method:

Locale.setDefault (Locale newLocale);

Several static methods of the Locale class allow you to get the default locale settings, or the locale specified by the locale parameter:

string getcountryo - the standard two-letter country code;

string getDispiayCountryO - the country is written with a word, usually displayed on the screen;

String getDisplayCountry (Locale locale) - the same for the specified locale.

The same methods are for language and variant.

You can view a list of all the locales defined for this JVM, and their parameters, displayed in standard form:

Locale [] getAvailableLocales ()

String!] GetlSOCountries ()

String [] getlSOLanguages ​​()

The installed locale is further used when outputting data in a local format.

Work with dates and times

Methods of working with dates and time indications are collected in two classes: Calendar and Date from the java.utii package .

The Date class object stores the number of milliseconds that have elapsed since January 1, 1970, 00:00:00 GMT. This is UNIX's "birthday", it's called " Epoch ".

The Date class is useful for counting time intervals in milliseconds.

You can get the current number of milliseconds that have elapsed since Epoch on the machine where the program runs, by the static method

System.currentTimeMillis ()

There are two constructors in the Date class. The Date () constructor enters the current time of the machine on which the program runs on the system clock into the newly created object, and the Date (long miiiisec) constructor enters the specified number.

You can get the value stored in the object using the long getTime () method ,

set new value by method   setTimedong newTime).

Three logical methods compare time counts:

boolean after (long when) - returns true if time   when more than this;

boolean before (long when) - returns true if the when time is less than the given time;

boolean after (Object when) - returns true if when is an object of the classca Date and the times are the same.

Two more methods, comparing time samples, return a negative number of type int , if the given time is less than the when argument; zero if the times are the same; a positive number if the given time is greater than the when argument:

int compareTo (Date when);

int compareTotobject when) - if when does not belong to objects of the class Date , an exception is thrown.

The conversion of milliseconds stored in objects of the Date class to the current time and date is performed by the methods of the calendar class.

Time zone and summer time

Methods for setting and changing the time zone (time zone) , as well as daylight saving time DST (Daylight Savings Time), are collected in the abstract class Timezone from the java.utii package . In the same package there is its implementation - a subclass of SimpleTimeZone .

In the class simpieTimeZon e there are three constructors, but most often the object is created by the static method getoefauito , which returns the time zone set on the machine running the program.

In these classes, there are many methods for working with time zones, but in most cases you only need to find out the time zone on the machine running the program, using the static getDefault () method, check if daylight saving time is taking place, useDaylightTime () using a logical method, and set the time zone method setDef ault (TimeZone zone).

Calendar class

The Calendar class is abstract; it contains general properties of calendars: Julian, Gregorian, and Lunar. In the Java API, there is only one implementation so far - a subclass of GregorianCalendar.

Since calendar is an abstract class, its instances are created by four static methods for a given locale and / or time zone:

Calendar getlnstance ()

Calendar getlnstance (Locale loc)

Calendar getlnstance (TimeZone tz)

Calendar getlnstance (TimeZone tz, Locale loc)

JANUARY integer constants are defined for working with months .

to DECEMBER , 3 to work with days of the week - constants MONDAY to SUNDAY .

The first day of the week can be recognized by the iFD method getFirstDayOfweek (), and set by the method setFirstDayOfWeek (int day), for example:

setFirstDayOfWeek (Calendar.MONDAY)

The remaining methods allow you to view the time and time zone or set them.

Subclass of GregorianCalendar

In the Gregorian calendar, two integer constants define eras: before Christ and AD (Anno Domini).

Seven constructors define a calendar by time, time zone, and / or locale:

GregorianCalendar ()

GregorianCalendar (int year, int month, int date)

GregorianCalendar (int year, int month, int date, int hour, int minute)

GregorianCalendar (int year, int month, int date,

int hour, int minute, int second)

GregorianCalendar (Locale loc)

GregorianCalendar (TimeZone tz)

GregorianCalendar (TimeZone tz, Locale loc)

After creating the object, you should determine the date of transition from the Julian calendar to the Gregorian calendar using the setGregorianChange method (Date date ). By default, this is October 15, 1582. In Russia, the transition was made on February 14, 1918, which means that the creation of the greg object should be done as follows:

GregorianCalendar greg = new GregorianCalendar (); greg.setGregorianChange (new

GregorianCalendar (1918, Calendar.FEBRUARY, 14) .getTime ());

You can find out if a year is a leap year in the Gregorian calendar, sLeapYear ().

The get (int field) method returns the calendar item specified by the field argument. The following static integer constants are defined for this argument in the Calendar class:

ERA WEEK_OF_YEAR DAY_OF_WEEK SECOND

YEAR WEEK_OF_MONTH DAY_OF_WEEK_IN_MONTH MILLISECOND

MONTH DAY_OF_YEAR HOUR_OF_DAY ZONE_OFFSET

DATE DAY_OF_MONTH MINUTE DST_OFFSET

Several set () methods using these constants set the appropriate values.

Date and Time Representation

Various ways of representing dates and times can be accomplished by methods compiled into the abstract class DateFormat and its subclass SimpleDateFormat FROM the Java package . text.

The DateFormat class offers four styles for representing dates and times:

the SHORT style represents the date and time in a short numerical form: 04/27/01 17:32; in US locale: 4/27/01 5:32 PM;

MEDIUM style sets the year in four digits and shows seconds: 04/27/2001 17:32:45; in the US locale, the month is represented by three letters;

LONG style represents a month with a word and adds a time zone: April 27, 2001 17:32:45 GMT + 03.-00;

FULL style in Russian is the same as LONG style; Another day of the week is added to the US locale.

There is also a DEFAULT style that matches the MEDIUM style.

When creating an object of the class simpieDateFormat, you can set a template in the constructor that defines some other format, for example:

SimpieDateFormat sdf = new SimpieDateFormat ("dd-MM-yyyy hh.iran"); System.out.println (sdf.format (new Date ()));

We will get the output in this form: 27-04-2001 17.32.

In the pattern, the letter d means the day of the month, m represents the month, y represents the year, h represents the hour, m indicates the minute. The remaining designations for the template are listed in the Software Documentation Class SimpieDateFormat . •

These lettering can be changed using the DateFormatSymbols class .

Not all locales can create an object of class SimpieDateFormat . In such cases, static DateFormat getinstanceo methods are used that return a DateFormat class object . Parameters of these methods are the style of presenting the date and time and, perhaps, the locale.

After creating an object, the format method of the DateFormat class returns a string with the date and time, according to the specified style. The argument is an object of the Date class.

For example:

System.out.println ("LONG:" + DateFormat.getDateTimelnstance (

DateFormat. LONG, DateFormat. LONG). format (new Date () •));

or

System.out.println ("FULL:" + DateFormat.getDateTimelnstance (

DateFormat.FULL, DateFormat.FULL, Locale.US) .format (new Date ()));

Getting random numbers

You can get a random non-negative number, strictly less than one, in the form of double type by using the static method random () of the class java.lang.Math.

The first time this method is accessed, a pseudo-random number generator is created, which is used later when obtaining the following random numbers.

More serious actions with random numbers can be organized using the methods of the Random class from the java.utii package. There are two constructors in the class:

Random (long seed) - creates a pseudo-random number generator that uses the number s eed to get started; Random () - selects the current time as the initial value. ;

By creating a generator, you can get random numbers of the appropriate type using the methods nextBoolean (), nextDouble (), nextFloat () (, nextGau.ssian (), next into, nextLong (), nextint (int max) or write down a sequence of random numbers in a predefined byte array bytes method nextBytes (byte [] bytes) .

Real random numbers evenly range from 0.0 inclusive to 1.0 exclusively. Integers random numbers are evenly distributed over the entire range of the corresponding type, with one exception: if the integer max is specified in the argument, then the range of random numbers will be from zero inclusive to max exclusively.

Copying arrays

In the System class from the java.iang package there is a static array copying method that is used by the Java execution system itself. This method works quickly and reliably, it is convenient to use it in programs. Syntax:

static void arraycopy (Object src, int src_ind, Object dest, int dest_ind, int count)

From the array pointed to by the src link, the count elements are copied, starting with the element with the index src_ind , into the array pointed to by the dest link, starting with its element with the index dest_ind.

All indexes must be specified so that the elements lie in the arrays, the types of arrays must be compatible, and primitive types must completely coincide. Array references must not be null .

The src and dest links can be the same, and an intermediate buffer is created for copying. The method can be used, for example, to shift elements in an array. After doing

int [] arr = {5, 6, 1, 8, 9, 1, 2, 3, 4, 5, -3, -7};

System.arraycopy (arr, 2, arr, 1, arr.length - 2);

we get ( 5, 7, 8, 9, 1, 2, 3, 4, 5, -3, -7, -7} .

Interaction with the system

The System class allows for some interaction with the system at runtime (run time ). But besides him for this there is a special class Runtime .

The Runtime class contains some methods for interacting with the JVM during program execution. Each application can receive only one instance of this class by the static getRuntime (} method. All calls to this method return a reference to the same object.

The methods fgeemetogogu () and totaiMemory () return the amount of free and all memory available to the JVM for placing objects, in bytes, as a number of type long. He should not rely on these numbers, because the amount of memory varies dynamically.

The exit method (int status) starts the shutdown process of the JVM and passes the status of the status to the operating system. By convention, non-zero status means abnormal termination. It is more convenient to use a similar method of the class system , which is static.

The hait (int status ) method immediately stops the JVM. It does not terminate running processes normally and should be used only in emergency situations.

The loadbibrary method (string libName) allows you to load a dynamic library at run time by its name libName .

The l oad (string fileName ) method loads the dynamic library by the file name fileName , in which it is stored.

However, instead of these methods it is more convenient to use static methods of the class system with the same names and arguments.

The gc () method starts the process of freeing unnecessary RAM ( garbage collection) . This process is periodically launched by the Java virtual machine itself and runs against a background with low priority, but it can also be started from the program. Again, it is more convenient to use the static System.gc () Method.

Finally, several exec () methods launch executable files in separate processes. The argument of these methods is the command line of the executable file.

For example , Runtime.getRuntime () .exec ("notepad" ) starts the Program

Notepad on the MS Windows platform.

The exec () methods return an instance of the process class that allows you to manage the running process. Using the destroy () method, you can stop the process; use the exitValue () method to get its exit code. waitFor () method

suspends the main subprocess until the running process ends. The three methods getlnputStream (), getOutputStream () and getErrorStream () ( return the input, output stream and error stream of the running process (see Chapter 18).


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Object oriented programming

Terms: Object oriented programming