Java 简明教程
Java - Data Structures
Java utility package 提供的数据结构非常强大并且执行各种功能。这些数据结构包括以下接口和类 -
The data structures provided by the Java utility package are very powerful and perform a wide range of functions. These data structures consist of the following interface and classes −
-
Enumeration
-
BitSet
-
Vector
-
Stack
-
Dictionary
-
Hashtable
-
Properties
现在所有这些类都已成为传统,而 Java-2 引入了一个称为 Collections Framework 的新框架,下一章将对此进行讨论:
All these classes are now legacy and Java-2 has introduced a new framework called Collections Framework, which is discussed in the next chapter −
The Enumeration
Enumeration interface 本身不是数据结构,但在其他数据结构的上下文中非常重要。Enumeration 接口定义了一种从数据结构中检索连续元素的方法。
The Enumeration interface isn’t itself a data structure, but it is very important within the context of other data structures. The Enumeration interface defines a means to retrieve successive elements from a data structure.
例如,Enumeration 定义了一个名为 nextElement 的方法,用于获取包含多个元素的数据结构中的下一个元素。
For example, Enumeration defines a method called nextElement that is used to get the next element in a data structure that contains multiple elements.
Example
以下是显示针对 Vector 使用 Enumeration 的示例。
Following is an example showing usage of Enumeration for a Vector.
import java.util.Vector;
import java.util.Enumeration;
public class EnumerationTester {
public static void main(String args[]) {
Enumeration<String> days;
Vector<String> dayNames = new Vector<>();
dayNames.add("Sunday");
dayNames.add("Monday");
dayNames.add("Tuesday");
dayNames.add("Wednesday");
dayNames.add("Thursday");
dayNames.add("Friday");
dayNames.add("Saturday");
days = dayNames.elements();
while (days.hasMoreElements()) {
System.out.println(days.nextElement());
}
}
}
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
为了对此接口有更详细的了解,请查看 The Enumeration 。
To have more detail about this interface, check The Enumeration.
The BitSet
BitSet class 实现了一组可以单独设置和清除的位或标记。
The BitSet class implements a group of bits or flags that can be set and cleared individually.
当需要保留一组布尔值时,这个类非常有用;你只需为每个值分配一个位,并在合适的情况下设置或清除它。
This class is very useful in cases where you need to keep up with a set of Boolean values; you just assign a bit to each value and set or clear it as appropriate.
Example
以下程序展示了位集数据结构支持的几种方法 −
The following program illustrates several of the methods supported by BitSet data structure −
import java.util.BitSet;
public class BitSetDemo {
public static void main(String args[]) {
BitSet bits1 = new BitSet(16);
BitSet bits2 = new BitSet(16);
// set some bits
for(int i = 0; i < 16; i++) {
if((i % 2) == 0) bits1.set(i);
if((i % 5) != 0) bits2.set(i);
}
System.out.println("Initial pattern in bits1: ");
System.out.println(bits1);
System.out.println("\nInitial pattern in bits2: ");
System.out.println(bits2);
// AND bits
bits2.and(bits1);
System.out.println("\nbits2 AND bits1: ");
System.out.println(bits2);
// OR bits
bits2.or(bits1);
System.out.println("\nbits2 OR bits1: ");
System.out.println(bits2);
// XOR bits
bits2.xor(bits1);
System.out.println("\nbits2 XOR bits1: ");
System.out.println(bits2);
}
}
Initial pattern in bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
Initial pattern in bits2:
{1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14}
bits2 AND bits1:
{2, 4, 6, 8, 12, 14}
bits2 OR bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
bits2 XOR bits1:
{}
The Vector
Vector class 类似于传统的 Java array ,但它可以根据需要增长以容纳新元素。
The Vector class is similar to a traditional Java array, except that it can grow as necessary to accommodate new elements.
和数组一样,可以根据向量中的索引访问向量对象的元素。
Like an array, elements of a Vector object can be accessed via an index into the vector.
使用 Vector 类的优点是,在创建时不必担心将其设置为特定的大小;它会在必要时自动缩小和增长。
The nice thing about using the Vector class is that you don’t have to worry about setting it to a specific size upon creation; it shrinks and grows automatically when necessary.
Example
下面的程序说明了 Vector 集合支持的几种方法:
The following program illustrates several of the methods supported by Vector collection −
import java.util.*;
public class VectorDemo {
public static void main(String args[]) {
// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " + v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " + v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " + (Integer)v.firstElement());
System.out.println("Last element: " + (Integer)v.lastElement());
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
// enumerate the elements in the vector.
Enumeration vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}
Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.
Elements in vector:
1 2 3 4 5.45 6.08 7 9.4 10 11 12
The Stack
Stack 类实现了元素的后进先出 (LIFO) 栈。
The Stack class implements a last-in-first-out (LIFO) stack of elements.
你可以从字面上将栈看成一个垂直的对象栈;当你添加一个新元素时,它会堆叠在其他元素之上。
You can think of a stack literally as a vertical stack of objects; when you add a new element, it gets stacked on top of the others.
当你从栈中拉出元素时,它是从顶部拉出的。换句话说,你添加到栈中的最后一个元素是返回的第一个元素。
When you pull an element off the stack, it comes off the top. In other words, the last element you added to the stack is the first one to come back off.
Example
以下程序说明了 Stack 集合支持的若干方法 -
The following program illustrates several of the methods supported by Stack collection −
import java.util.*;
public class StackDemo {
static void showpush(Stack st, int a) {
st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}
static void showpop(Stack st) {
System.out.print("pop -> ");
Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}
public static void main(String args[]) {
Stack st = new Stack();
System.out.println("stack: " + st);
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try {
showpop(st);
} catch (EmptyStackException e) {
System.out.println("empty stack");
}
}
}
stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack
The Dictionary
Dictionary 类是一个抽象类,它定义了向值映射键的数据结构。
The Dictionary class is an abstract class that defines a data structure for mapping keys to values.
当你想通过特定键而不是整数索引访问数据时,这很有用。
This is useful in cases where you want to be able to access data via a particular key rather than an integer index.
由于 Dictionary 类是抽象的,它只提供键映射的数据结构的框架,而不是特定的实现。
Since the Dictionary class is abstract, it provides only the framework for a key-mapped data structure rather than a specific implementation.
Example
以下示例演示了如何使用 Java Dictionary keys() 方法。我们使用 Integer、Integer 的 Hashtable 对象创建一个字典实例。然后我们向其中添加了一些元素。使用 keys() 方法检索枚举,然后迭代枚举以打印字典的键。
The following example shows the usage of Java Dictionary keys() method. We’re creating a dictionary instance using Hashtable object of Integer, Integer. Then we’ve added few elements to it. An enumeration is retrieved using keys() method and enumeration is then iterated to print the keys of the dictionary.
package com.tutorialspoint;
import java.util.Enumeration;
import java.util.Dictionary;
import java.util.Hashtable;
public class DictionaryDemo {
public static void main(String[] args) {
// create a new hashtable
Dictionary<Integer, Integer> dictionary = new Hashtable<>();
// add 2 elements
dictionary.put(1, 1);
dictionary.put(2, 2);
Enumeration<Integer> enumeration = dictionary.keys();
while(enumeration.hasMoreElements()) {
System.out.println(enumeration.nextElement());
}
}
}
2
1
The Hashtable
Hashtable 类提供了一种基于某些用户定义的键结构来组织数据的方法。
The Hashtable class provides a means of organizing data based on some user-defined key structure.
举例来说,在一个地址列表哈希表中,你可以根据 ZIP 编码这样的键存储和对数据进行排序,而不是按一个人的姓名进行排序。
For example, in an address list hash table you could store and sort data based on a key such as ZIP code rather than on a person’s name.
键与哈希表之间的具体含义完全取决于哈希表的用法和它所包含的数据。
The specific meaning of keys with regard to hash tables is totally dependent on the usage of the hash table and the data it contains.
Example
以下示例演示了如何使用 Java Hashtable contains() 方法来检查 Hashtable 中是否存在某个值。我们创建了一个 Integer、Integer 的 Hashtable 对象。然后添加了一些条目,打印出表格,并使用 contains() 检查表格中的两个值。
The following example shows the usage of Java Hashtable contains() method to check if a value is present in a Hashtable or not. We’ve created a Hashtable object of Integer,Integer. Then few entries are added, table is printed and using contains() we’re checking about two values in the table.
package com.tutorialspoint;
import java.util.Hashtable;
public class HashtableDemo {
public static void main(String args[]) {
// create hash table
Hashtable<Integer,Integer> hashtable = new Hashtable<>();
// populate hash table
hashtable.put(1, 1);
hashtable.put(2, 2);
hashtable.put(3, 3);
System.out.println("Initial table elements: " + hashtable);
System.out.println("Hashtable contains 2 as value: " + hashtable.contains(2));
System.out.println("Hashtable contains 4 as value: " + hashtable.contains(4));
}
}
Initial table elements: {3=3, 2=2, 1=1}
Hashtable contains 2 as value: true
Hashtable contains 4 as value: false
The Properties
属性是散列表的一个子类。它用于维护值列表,其中键是一个字符串,值也是一个字符串。
Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String.
许多其他 Java 类都使用 Properties 类。例如,它是 System.getProperties( ) 在获取环境值时返回的对象类型。
The Properties class is used by many other Java classes. For example, it is the type of object returned by System.getProperties( ) when obtaining environmental values.
Example
以下示例演示了如何使用 Java Properties getProperty(String key) 方法根据 Properties 中的键获取值。我们创建了一个 Properties 对象。然后添加了一些条目。使用 getProperty() 方法,检索并打印一个值。
The following example shows the usage of Java Properties getProperty(String key) method to get a value based on a key from a Properties. We’ve created a Properties object. Then few entries are added. Using getProperty() method, a value is retrieved and printed.
package com.tutorialspoint;
import java.util.Properties;
public class PropertiesDemo {
public static void main(String[] args) {
Properties properties = new Properties();
//populate properties object
properties.put("1", "tutorials");
properties.put("2", "point");
properties.put("3", "is best");
System.out.println("Properties elements: " + properties);
System.out.println("Value: " + properties.getProperty("1"));
}
}