Java 简明教程
Java.util Package Tutorial
Java - java.util Package
java.util 包是 Java SDK 的标准包。它包含集合框架、旧集合类、事件模型、日期和时间设施、国际化以及其他实用类。此包非常有用,因为它提供了 ArrayList、HashMap、Set 等常用集合。Java.util 提供 StrinTokenizer 类用于字符串操作,同样,其他实用类用于事件模型处理、日期和时间操作等等。此参考将引导您了解 java.util 包中可用且实用的方法。
The java.util package is a standard package of Java SDK. It contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes. This package is very useful as it provides commonly used Collections like ArrayList, HashMap, Set etc. Java.util provides StrinTokenizer classes for String operations and similarly other utility classes for event model handlings, date and time operations and lot more. This reference will take you through simple and practical methods available in java.util package.
Importing java.util Package
作为 Java 的内置包,我们无需下载任何 java.util 包的外部库,并且可以使用以下语法导入其所有类:
Being an inbuilt package of Java, we’re not required to download any external library for java.util package and its all classes can be imported using following syntax:
import java.util.*;
这里我们用 * 运算符从 java.util 包导入所有类,现在任何类都可以在程序中使用。对于特定类,例如 ArrayList,我们可以使用以下语法导入类:
Here we’ve used * operator to import all classes from java.util package and now any class can be used in the program. In case of specific class, for example ArrayList, we can import a class using following syntax:
import java.util.ArrayList;
Why java.util Package is used in Java Programs
Java.util 包类包含实用类,如集合框架、字符串操作实用程序、日期和时间操作实用程序。以下列出了 java.util 包的类类别。
Java.util package classes contains utility classes like collections frameworks, String operations utilities, Date and Time operations utilities. Following list shows some of the categories of classes of java.util package.
-
Collections − ArrayList, HashMap, Dictionary are few of the classes of large set of Collection classes availble in java.util package. These classes provides commonly used operations on large data sets.
-
Date Time Operations − GregorianCalendar, Timezone are some of the classes of utility classes availble in java.util package. These classes provides commonly used operations on date and time.
-
String Manipulations − StringTokenizer is an important utility class availble in java.util package. This class provides a lot of operations to manipulate strings.
-
Enumerations − Enumeration class of java.util package provides operations on set of values like iterations, comparison etc.
-
Exceptions − java.util package contains various commonly occuring exceptions like ConcurrentModificationException, InputMismatchException etc.
Important classes in java.util Package
以下是 java.util.package 中重要类的列表:
Following is the list of important classes in java.util.package:
-
ArrayDeque − This class provides resizable-array and implements the Deque interface. This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces.
-
ArrayList − This class provides resizable-array and implements the List interface. The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed.
-
Arrays − This class contains a static factory that allows arrays to be viewed as lists. The ArrayList class contains various methods for manipulating arrays (such as sorting and searching).
-
BitSet − This class creates a special type of array that holds bit values. The BitSet array can increase in size as needed. This makes it similar to a vector of bits. This is a legacy class but it has been completely re-engineered in Java 2, version 1.4. The Java BitSet class implements a vector of bits that grows as needed.
-
Calendar − This class is an abstract class that provides methods for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next week.
-
Collections − This class consists exclusively of static methods that operate on or return collections.
-
Currency − This class represents a currency. The Currency class is designed so that there’s never more than one Currency instance for any given currency, this is the reason behind no public constructor.
-
Date − This class represents a specific instant in time, with millisecond precision.
-
Dictionary − This class is the abstract parent of any class, such as Hashtable, which maps keys to values.
-
EnumMap − This class is a specialized Map implementation for use with enum keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created.
-
EnumSet − This class is a specialized Set implementation for use with enum keys. All of the keys in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created.
-
Formatter − This class provides support for layout justification and alignment, common formats for numeric, string, and date/time data, and locale-specific output.
-
GregorianCalendar − This class is a concrete subclass of Calendar and provides the standard calendar system used by most of the world. It is a hybrid calendar that supports both the Julian and Gregorian calendar systems with the support of a single discontinuity, which corresponds by default to the Gregorian date when the Gregorian calendar was instituted.
-
HashMap − This class is the Hash table based implementation of the Map interface.
-
HashSet − This class implements the Set interface, backed by a hash table.
-
HashTable − This class implements a hashtable, which maps keys to values.
-
IdentityHashMap − This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values).
-
LinkedHashMap − This class is Hash table and Linked list implementation of the Map interface, with predictable iteration order.
-
LinkedHashSet − This class is Hash table and Linked list implementation of the Set interface, with predictable iteration order.
-
LinkedList − This class operations perform we can expect for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.
-
ListResourceBundle − This class is an abstract subclass of ResourceBundle that manages resources for a locale in a convenient and easy to use list.
-
Locale − This class object represents a specific geographical, political, or cultural region.
-
Observable − This class represents an observable object, or "data" in the model-view paradigm. The class can be subclassed to represent an object that the application wants to have observed.
-
PriorityQueue − This class is an unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.
-
Properties − This class is a class which represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream.
-
PropertyPermission − This class is a class for property permissions.
-
PropertyResourceBundle − This class is a concrete subclass of ResourceBundle that manages resources for a locale using a set of static strings from a property file.
-
Random − This class instance is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula.
-
ResourceBundle − This class contain locale-specific objects. The class allows you to write programs that can be easily localized, or translated, into different languages.
-
ResourceBundle.Control − This class collaborates with the factory methods for loading resource bundles.
-
Scanner − This class is a simple text scanner which can parse primitive types and strings using regular expressions.
-
ServiceLoader − This class is a simple service-provider loading facility. Service loaders always execute in the security context of the caller.Trusted system code should typically invoke the methods in this class, and the methods of the iterators which they return, from within a privileged security context.
-
SimpleTimeZone − This class is a concrete subclass of TimeZone that represents a time zone for use with a Gregorian calendar.
-
Stack − Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own.
-
StringTokenizer − This class allows an application to break a string into tokens. This class is a legacy class that is retained for compatibility reasons although its use is discouraged in new code.
-
Timer − This class provides facility for threads to schedule tasks for future execution in a background thread.
-
TimerTask − This class represents a task that can be scheduled for one-time or repeated execution by a Timer.
-
TimeZone − This class represents a time zone offset, and also figures out daylight savings.
-
TreeMap − This class is the Red-Black tree based implementation of the Map interface. The TreeMap class guarantees that the Map will be in ascending key order.
-
TreeSet − This class implements the Set interface. The TreeSet class guarantees that the Set will be in ascending key order and backed by a TreeSet.
-
UUID − This class class represents an immutable universally unique identifier (UUID). There are four different basic types of UUIDs: time-based, DCE security, name-based, and randomly generated UUIDs.
-
Vector − Vector implements a dynamic array. The Vector class implements a growable array of objects. Similar to an Array, it contains components that can be accessed using an integer index.
Examples of java.util Package
针对以下范例练习 java.util 程序包类的概念和用法。
Practice the following examples to learn the concept and usage of java.util package clasess.
Example of java.util.ArrayList
以下程序演示了 ArrayList 支持的多种方法 -
The following program illustrates several of the methods supported by ArrayList −
package com.tutorialspoint;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " + al.size());
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());
// display the array list
System.out.println("Contents of al: " + al);
// Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}
这会产生以下结果 −
This will produce the following result −
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
Example of java.util.Date
此 Java 示例演示了 Date class 的 from() 方法以获取当前时间的 Date 实例。
This Java example demonstrates the from() method of Date class to get Date instance of current time.
package com.tutorialspoint;
import java.time.Instant;
// Import the Date package
import java.util.Date;
// Main public class
public class DateDemo {
public static void main(String[] args) {
// create a date of current time
Date date = Date.from(Instant.now());
// print the date instance
System.out.println("Date: " + date.toString());
}
}
让我们编译并运行上述程序,这将生成以下结果 −
Let us compile and run the above program, this will produce the following result −
Date: Mon Apr 01 10:20:08 IST 2024
Example of java.util.Random
以下示例展示了 Java Random doubles() 方法的使用。首先,我们创建了一个 Random 对象,然后使用 doubles() 检索一个随机双精度值的流,并打印第一个值。
The following example shows the usage of Java Random doubles() method. Firstly, we’ve created a Random object and then using doubles() we retrieved a stream of random double values and printed first value.
package com.tutorialspoint;
import java.util.Random;
import java.util.stream.DoubleStream;
public class RandomDemo {
public static void main( String args[] ) {
// create random object
DoubleStream randomNoStream = new Random().doubles();
// print a random double value
randomNoStream.limit(1).forEach( i -> System.out.println(i));
}
}
让我们编译并运行以上的程序,这会生成以下结果:
Let us compile and run the above program, this will produce the following result.
0.5129590222446587
When java.util Package is Used?
每当我们需要操作集合、字符串、执行事件处理等时,我们都可以依靠 java.util 包中存在的实用程序类。此参考针对初学者准备,可以帮助他们理解 Java.util 包中所有可用方法的相关基本功能。
Whenever we need to manipulate collections, Strings, perform event handling etc, we can rely on utility classes present in java.util package. This reference has been prepared for the beginners to help them understand the basic functionality related to all the methods available in Java.util package.