在Javaeye上看到一篇贴子,还不错,都是Java编码中比较实用的代码。也可以直接去Java参考中文站去阅读。
java.util
e331. 产生一个随机数
Random rand = new Random();
// Random integers
int i = rand.nextInt();
// Continually call nextInt() for more random integers ...
// Random integers that range from from 0 to n
int n = 10;
i = rand.nextInt(n+1);
// Random bytes
byte[] bytes = new byte[5];
rand.nextBytes(bytes);
// Other primitive types
boolean b = rand.nextBoolean();
long l = rand.nextLong();
float f = rand.nextFloat(); // 0.0 <= f < 1.0
double d = rand.nextDouble(); // 0.0 <= d < 1.0
// Create two random number generators with the same seed
long seed = rand.nextLong();
rand = new Random(seed);
Random rand2 = new Random(seed);
e332. 将一个字符串分解成字
String aString = "word1 word2 word3";
StringTokenizer parser = new StringTokenizer(aString);
while (parser.hasMoreTokens()) {
processWord(parser.nextToken());
}
e333. 建立一个定制事件
A new custom event must extends EventObject
. Moreover, an event listener interface must be declared to allow objects to receive the new custom event. All listeners must extend from EventListener
.
This example demonstrates all the steps necessary to create a new custom event.
// Declare the event. It must extend EventObject. public class MyEvent extends EventObject { public MyEvent(Object source) { super(source); } } // Declare the listener class. It must extend EventListener. // A class must implement this interface to get MyEvents. public interface MyEventListener extends EventListener { public void myEventOccurred(MyEvent evt); } // Add the event registration and notification code to a class. public class MyClass { // Create the listener list protected javax.swing.event.EventListenerList listenerList = new javax.swing.event.EventListenerList(); // This methods allows classes to register for MyEvents public void addMyEventListener(MyEventListener listener) { listenerList.add(MyEventListener.class, listener); } // This methods allows classes to unregister for MyEvents public void removeMyEventListener(MyEventListener listener) { listenerList.remove(MyEventListener.class, listener); } // This private class is used to fire MyEvents void fireMyEvent(MyEvent evt) { Object[] listeners = listenerList.getListenerList(); // Each listener occupies two elements - the first is the listener class // and the second is the listener instance for (int i=0; i<listeners.length; i+=2) { if (listeners[i]==MyEventListener.class) { ((MyEventListener)listeners[i+1]).myEventOccurred(evt); } } } }
Here's an example of how to register for MyEvents.
MyClass c = new MyClass(); // Register for MyEvents from c c.addMyEventListener(new MyEventListener() { public void myEventOccurred(MyEvent evt) { // MyEvent was fired } }); e334. 实现一个简单的事件通知器
TheObserver
andObservable
classes are superseded by a more elaborate event framework (see e333 建立一个定制事件). However, these two classes can still be useful for implementing a simple event notifier.
// Declare the model class MyModel extends Observable { // The setChanged() protected method must overridden to make it public public synchronized void setChanged() { super.setChanged(); } }
// Create the model
MyModel model = new MyModel();
// Register for events
model.addObserver(new Observer() {
public void update(Observable o, Object arg) {
}
});
// Indicate that the model has changed
model.setChanged();
// Fire an event to all the views
Object arg = "some information about the event";
model.notifyObservers(arg);
e335. 列出所有可用的地区
Locale[] locales = Locale.getAvailableLocales();
for (int i=0; i<locales.length; i++) {
// Get the 2-letter language code
String language = locales[i].getLanguage();
// Get the 2-letter country code; may be equal to ""
String country = locales[i].getCountry();
// Get localized name suitable for display to the user
String locName = locales[i].getDisplayName();
}
Here's a sample of output using a default locale of Locale.ENGLISH
:
Language Code, Country Code, Localized Name ar, , Arabic ar, AE, Arabic (United Arab Emirates) ar, BH, Arabic (Bahrain) ar, DZ, Arabic (Algeria) ar, EG, Arabic (Egypt) ar, IQ, Arabic (Iraq) ar, JO, Arabic (Jordan) ar, KW, Arabic (Kuwait) ar, LB, Arabic (Lebanon)Here's a sample of output using a default locale of
Locale.FRENCH
:
Language Code, Country Code, Localized Name ar, , arabe ar, AE, arabe (Emirats Arabes Unis) ar, EG, arabe (Egypte) ar, IQ, arabe (Irak) ar, JO, arabe (Jordanie) ar, KW, arabe (Koweit) ar, LB, arabe (Liban)
e336. 设置默认地区
There are two ways to change the default locale. The first is to set it on the command line:
> java -Duser.language=2-char-language-code -Duser.region=2-char-country-code MyApp // Set only language code > java -Duser.language=fr -Duser.region= MyApp // Set language and country code > java -Duser.language=fr -Duser.region=CA MyAppThe second way to change the default locale is to call
Locale.setDefault()
:
// Get default locale Locale locale = Locale.getDefault(); // Set the default locale to pre-defined locale Locale.setDefault(Locale.FRENCH); // Set the default locale to custom locale locale = new Locale("fr", "CA"); Locale.setDefault(locale);
e337. 将一个值与一个对象联系起来
This example demonstrates how to associate a value with an arbitrary object. The technique involves saving the object and the associated value as a key/value pair in anIdentityHashMap
. AHashMap
cannot be used for this purpose since if two objects happen to equal via theObject.equals()
method, one of the objects will not be stored.
// Create the map Map objMap = new IdentityHashMap(); // Add the object and value pair to the map Object o1 = new Integer(123); Object o2 = new Integer(123); objMap.put(o1, "first"); objMap.put(o2, "second"); // Retrieve the value associated with the objects Object v1 = objMap.get(o1); // first Object v2 = objMap.get(o2); // second
Arrays
--------------------------------------------------------------------------------
e338. 数组比较
// null arrays are equal
boolean[] bArr1 = null;
boolean[] bArr2 = null;
boolean b = Arrays.equals(bArr1, bArr2); // true
// Compare two boolean arrays
bArr1 = new boolean[]{true, false};
bArr2 = new boolean[]{true, false};
b = Arrays.equals(bArr1, null); // false
b = Arrays.equals(bArr1, bArr2); // true
// There are equals() methods for all eight primitive types
b = Arrays.equals(new byte[]{0}, new byte[]{0}); // true
b = Arrays.equals(new char[]{'a'}, new char[]{'a'}); // true
b = Arrays.equals(new short[]{0}, new short[]{0}); // true
b = Arrays.equals(new int[]{0}, new int[]{0}); // true
b = Arrays.equals(new long[]{0L}, new long[]{0L}); // true
b = Arrays.equals(new float[]{0F}, new float[]{0F}); // true
b = Arrays.equals(new double[]{0D}, new double[]{0D}); // true
// When comparing Object arrays, null elements are equal.
// If the elements are not null, Object.equals() is used.
b = Arrays.equals(new String[]{"a"}, new String[]{"a"}); // true
b = Arrays.equals(new String[]{null}, new String[]{null}); // true
b = Arrays.equals(new String[]{"a"}, new String[]{null}); // false
e1074. 装填数组
The Arrays
class has conveninent methods for filling arrays of all eight primitive types:
boolean[] booleanArr = new boolean[10]; boolean booleanFillValue = false; Arrays.fill(booleanArr, booleanFillValue); byte[] byteArr = new byte[10]; byte byteFillValue = (byte)0xFF; Arrays.fill(byteArr, byteFillValue); char[] charArr = new char[10]; char charFillValue = 0xFF; Arrays.fill(charArr, charFillValue); short[] shortArr = new short[10]; short shortFillValue = 0xFF; Arrays.fill(shortArr, shortFillValue); int[] intArr = new int[10]; int intFillValue = -1; Arrays.fill(intArr, intFillValue); long[] longArr = new long[10]; long longFillValue = -1; Arrays.fill(longArr, longFillValue); float[] floatArr = new float[10]; float floatFillValue = -1; Arrays.fill(floatArr, floatFillValue); double[] doubleArr = new double[10]; double doubleFillValue = -1; Arrays.fill(doubleArr, doubleFillValue);
There is also a method for filling object arrays:
String[] StringArr = new String[1]; String StringFillValue = ""; Arrays.fill(StringArr, StringFillValue);
By default, the nine fill methods shown above set all the elements in the array with the fill value. Each fill method has an overloaded version that can restrict the fill to a contiguous range of elements:
// Fill elements 0, 1, 2, and 3; the end index is exclusive int startIndex = 0; int endIndex = 4; Arrays.fill(booleanArr, startIndex, endIndex, booleanFillValue); Arrays.fill(byteArr, startIndex, endIndex, byteFillValue); Arrays.fill(charArr, startIndex, endIndex, charFillValue); Arrays.fill(shortArr, startIndex, endIndex, shortFillValue); Arrays.fill(intArr, startIndex, endIndex, intFillValue); Arrays.fill(longArr, startIndex, endIndex, longFillValue); Arrays.fill(floatArr, startIndex, endIndex, floatFillValue); Arrays.fill(doubleArr, startIndex, endIndex, doubleFillValue); Arrays.fill(StringArr, startIndex, endIndex, StringFillValue); e339. 打乱一个列表或数组的元素
Use Collections.shuffle()
to randomly reorder the elements in a list.
// Create a list List list = new ArrayList(); // Add elements to list // Shuffle the elements in the list Collections.shuffle(list); // Create an array String[] array = new String[]{"a", "b", "c"}; // Shuffle the elements in the array Collections.shuffle(Arrays.asList(array));
e340. 将一个收集器装换成一个数组
// Create an array containing the elements in a list Object[] objectArray = list.toArray(); MyClass[] array = (MyClass[])list.toArray(new MyClass[list.size()]); // Create an array containing the elements in a set objectArray = set.toArray(); array = (MyClass[])set.toArray(new MyClass[set.size()]); // Create an array containing the keys in a map objectArray = map.keySet().toArray(); array = (MyClass[])map.keySet().toArray(new MyClass[set.size()]); // Create an array containing the values in a map objectArray = map.values().toArray(); array = (MyClass[])map.values().toArray(new MyClass[set.size()]); e341. 将一个数组转换成一个收集器
// Fixed-size list List list = Arrays.asList(array); // Growable list list = new LinkedList(Arrays.asList(array)); // Duplicate elements are discarded Set set = new HashSet(Arrays.asList(array));
Collections
--------------------------------------------------------------------------------
e342. 实现一个队列
LinkedList queue = new LinkedList();
// Add to end of queue
queue.add(object);
// Get head of queue
Object o = queue.removeFirst();
// If the queue is to be used by multiple threads,
// the queue must be wrapped with code to synchronize the methods
queue = (LinkedList)Collections.synchronizedList(queue);
e343. 实现一个栈
LinkedList stack = new LinkedList();
// Push on top of stack
stack.addFirst(object);
// Pop off top of stack
Object o = stack.getFirst();
// If the queue is to be used by multiple threads,
// the queue must be wrapped with code to synchronize the methods
stack = (LinkedList)Collections.synchronizedList(stack);
e344. 实现一个最近最少使用的(LRU)高速缓存
// Create cache
final int MAX_ENTRIES = 100;
Map cache = new LinkedHashMap(MAX_ENTRIES+1, .75F, true) {
// This method is called just after a new entry has been added
public boolean removeEldestEntry(Map.Entry eldest) {
return size() > MAX_ENTRIES;
}
};
// Add to cache
Object key = "key";
cache.put(key, object);
// Get object
Object o = cache.get(key);
if (o == null && !cache.containsKey(key)) {
// Object not in cache. If null is not a possible value in the cache,
// the call to cache.contains(key) is not needed
}
// If the cache is to be used by multiple threads,
// the cache must be wrapped with code to synchronize the methods
cache = (Map)Collections.synchronizedMap(cache);
e345. 遍历一个收集器中的元素
This example demonstrates how to iterate over the elements of various types of collections.
// For a set or list for (Iterator it=collection.iterator(); it.hasNext(); ) { Object element = it.next(); } // For keys of a map for (Iterator it=map.keySet().iterator(); it.hasNext(); ) { Object key = it.next(); } // For values of a map for (Iterator it=map.values().iterator(); it.hasNext(); ) { Object value = it.next(); } // For both the keys and values of a map for (Iterator it=map.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry)it.next(); Object key = entry.getKey(); Object value = entry.getValue(); }
e346. 用收集器存储基本类型
Collections can only store objects, not primitive types like int
and double
. Primitive types must be placed in a wrapper object before they can be placed in a collection. This example demonstrates the storing of int
values in a Map
.
See also: e58 包装基本类型为对象.
// Create map Map map = new HashMap(); // Create int wrapper object Integer refInt = new Integer(123); // Store int in map map.put("key", refInt); // Get int value from map refInt = (Integer)map.get("key"); // Get the integer value from wrapper object int i = refInt.intValue();
e347. 建立一个收集器的副本
These examples create a shallow copy of a collection. That is, the new collection contains references to same objects as the source collection; the objects are not cloned.
List stuff = Arrays.asList(new String[]{"a", "b"}); // Make a copy of a list List list = new ArrayList(stuff); List list2 = new LinkedList(list); // Make a copy of a set Set set = new HashSet(stuff); Set set2 = new TreeSet(set); // Make a copy of a map Map map = new HashMap(); // Add key/value pairs ... Map map2 = new TreeMap(map);
e348. 将一个收集器设为只读的
将一个收集器设为只读的 involves wrapping the collection in another object whose mutation methods all throw UnsupportedOperationException
.
List stuff = Arrays.asList(new String[]{"a", "b"}); // Make a list read-only List list = new ArrayList(stuff); list = Collections.unmodifiableList(list); try { // Try modifying the list list.set(0, "new value"); } catch (UnsupportedOperationException e) { // Can't modify } // Make a set read-only Set set = new HashSet(stuff); set = Collections.unmodifiableSet(set); // Make a map read-only Map map = new HashMap(); // Add key/value pairs ... map = Collections.unmodifiableMap(map);
Lists
--------------------------------------------------------------------------------
e349. 建立一个列表
// Create the list
List list = new LinkedList(); // Doubly-linked list
list = new ArrayList(); // List implemented as growable array
// Append an element to the list
list.add("a");
// Insert an element at the head of the list
list.add(0, "b");
// Get the number of elements in the list
int size = list.size(); // 2
// Retrieving the element at the end of the list
Object element = list.get(list.size()-1); // a
// Retrieving the element at the head of the list
element = list.get(0); // b
// Remove the first occurrence of an element
boolean b = list.remove("b"); // true
b = list.remove("b"); // false
// Remove the element at a particular index
element = list.remove(0); // a
e350. 将一个列表排序
// Create a list
String[] strArray = new String[] {"z", "a", "C"};
List list = Arrays.asList(strArray);
// Sort
Collections.sort(list);
// C, a, z
// Case-insensitive sort
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
// a, C, z
// Reverse-order sort
Collections.sort(list, Collections.reverseOrder());
// z, a, C
// Case-insensitive reverse-order sort
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
Collections.reverse(list);
// z, C, a
e351. 对列表进行操作
See also e349 建立一个列表.
// Create the lists
List list1 = new ArrayList();
List list2 = new ArrayList();
// Add elements to the lists ...
// Copy all the elements from list2 to list1 (list1 += list2)
// list1 becomes the union of list1 and list2
list1.addAll(list2);
// Remove all the elements in list1 from list2 (list1 -= list2)
// list1 becomes the asymmetric difference of list1 and list2
list1.removeAll(list2);
// Get the intersection of list1 and list2
// list1 becomes the intersection of list1 and list2
list1.retainAll(list2);
// Remove all elements from a list
list1.clear();
// Truncate the list
int newSize = 2;
list1.subList(newSize, list1.size()).clear();
e1075. 创建一个确切型别的列表
Generics can be used to create a list that will hold only objects of a certain type. This example creates a list of Integer
objects.
List<Integer> intlist = new ArrayList<Integer>(); intlist.add(new Integer(123)); // intlist.add("hello"); <- Syntax errorA list declared to hold objects of a type T can also hold objects that extend from T. In this example, a list is created to hold
Number
objects. Both
Integer
and
Float
are subclasses of
Number
.
List<Number> numlist = new ArrayList<Number>(); numlist.add(new Integer(123)); numlist.add(new Float(123));Note that although
null
is not a subclass of any type, if the collection supports
null
values, it can be added to the type-specific collection.
intlist.add(null);A value retrieved from a type-specific list does not need to be casted. In this example, a URL value is retrieved and used without an explicit cast.
List<URL> urlList = new ArrayList<URL>(); try { urlList.add(new URL("http://javaref.cn")); } catch (MalformedURLException e) { } String s = urlList.get(0).getHost();
Sets
--------------------------------------------------------------------------------
e352. 建立一个集合
A set is a collection that holds unique values. Adding a value that's already in the set has no effect.
// Create the set Set set = new HashSet(); // Add elements to the set set.add("a"); set.add("b"); set.add("c"); // Remove elements from the set set.remove("c"); // Get number of elements in set int size = set.size(); // 2 // Adding an element that already exists in the set has no effect set.add("a"); size = set.size(); // 2 // Determining if an element is in the set boolean b = set.contains("a"); // true b = set.contains("c"); // false // Iterating over the elements in the set Iterator it = set.iterator(); while (it.hasNext()) { // Get element Object element = it.next(); } // Create an array containing the elements in the set (in this case a String array) String[] array = (String[])set.toArray(new String[set.size()]);
e353. 操作一个集合
See also e352 建立一个集合.
// Create the sets Set set1 = new HashSet(); Set set2 = new HashSet(); // Add elements to the sets ... // Copy all the elements from set2 to set1 (set1 += set2) // set1 becomes the union of set1 and set2 set1.addAll(set2); // Remove all the elements in set1 from set2 (set1 -= set2) // set1 becomes the asymmetric difference of set1 and set2 set1.removeAll(set2); // Get the intersection of set1 and set2 // set1 becomes the intersection of set1 and set2 set1.retainAll(set2); // Remove all elements from a set set1.clear();
e354. 建立一个保持插入次序的集合
Set set = new LinkedHashSet(); // Add some elements set.add("1"); set.add("2"); set.add("3"); set.add("2"); // List the elements for (Iterator it=set.iterator(); it.hasNext(); ) { Object o = it.next(); } // [1, 2, 3]
Hash Tables
--------------------------------------------------------------------------------
e355. 建立一个散列表
A hash table, or map, holds key/value pairs.
// Create a hash table Map map = new HashMap(); // hash table map = new TreeMap(); // sorted map // Add key/value pairs to the map map.put("a", new Integer(1)); map.put("b", new Integer(2)); map.put("c", new Integer(3)); // Get number of entries in map int size = map.size(); // 2 // Adding an entry whose key exists in the map causes // the new value to replace the old value Object oldValue = map.put("a", new Integer(9)); // 1 // Remove an entry from the map and return the value of the removed entry oldValue = map.remove("c"); // 3 // Iterate over the keys in the map Iterator it = map.keySet().iterator(); while (it.hasNext()) { // Get key Object key = it.next(); } // Iterate over the values in the map it = map.values().iterator(); while (it.hasNext()) { // Get value Object value = it.next(); } e356. 建立一个维护插入次序的MAP
Map map = new LinkedHashMap(); // Add some elements map.put("1", "value1"); map.put("2", "value2"); map.put("3", "value3"); map.put("2", "value4"); // List the entries for (Iterator it=map.keySet().iterator(); it.hasNext(); ) { Object key = it.next(); Object value = map.get(key); } // [1=value1, 2=value4, 3=value3]
e357. 自动从三列表中删除没有引用的元素
When a key is added to a map, the map will prevent the key from being garbage-collected. However, a weak map will automatically remove a key if the key is not being referenced by any other object. An example where this type of map might be useful is a registry where a registrant is automatically removed after it is garbage-collected.
// Create the weak map Map weakMap = new WeakHashMap(); // Add a key to the weak map weakMap.put(keyObject, valueObject); // Get all keys that are still being referenced Iterator it = weakMap.keySet().iterator(); while (it.hasNext()) { // Get key Object key = it.next(); }The weak map does not automatically release the value if it is no longer used. To enable automatically release of the value, the value must be wrapped in a
WeakReference
object:
WeakReference weakValue = new WeakReference(valueObject); weakMap.put(keyObject, weakValue); // Get all keys that are still being referenced and check whether // or not the value has been garbage-collected it = weakMap.keySet().iterator(); while (it.hasNext()) { // Get key Object key = it.next(); weakValue = (WeakReference)weakMap.get(key); if (weakValue == null) { // Value has been garbage-collected } else { // Get value valueObject = weakValue.get(); } }
e1076. 创建一个确切型别的Map
Generics can be used to create a map that will hold only objects of a certain type. This example creates a map whose keys areInteger
objects and values areString
objects.
Map<Integer, String> map = new HashMap<Integer, String>(); map.put(1, "first"); map.put(2, "second"); // map.put(1, 2); <- Syntax errorA map declared to hold objects of a type T can also hold objects that extend from T. In this example, a map is created to hold
Number
objects as keys. Both
Integer
and
Float
are subclasses of
Number
.
Map<Number, String> numMap = new HashMap<Number, String>(); numMap.put(.5, "half"); numMap.put(1, "first");Note that although
null
is not a subclass of any type, if the collection supports
null
values, it can be added to the type-specific collection.
map.put(null, null);A value retrieved from a type-specific collection does not need to be casted. In this example, a URL value is retrieved and used without an explicit cast.
Map<String, URL> urlMap = new HashMap<String, URL>(); try { urlMap.put("java", new URL("http://javaref.cn")); } catch (MalformedURLException e) { } String s = urlMap.get("java").getHost();
Sorted Collections
--------------------------------------------------------------------------------
e358. 建立一个排序的集合
A sorted set is a set that maintains its items in a sorted order. Inserts and retrievals are more expensive in a sorted set but iterations over the set is always in order.
See also e352 建立一个集合.
// Create the sorted set SortedSet set = new TreeSet(); // Add elements to the set set.add("b"); set.add("c"); set.add("a"); // Iterating over the elements in the set Iterator it = set.iterator(); while (it.hasNext()) { // Get element Object element = it.next(); } // The elements are iterated in order: a, b, c // Create an array containing the elements in a set (in this case a String array). // The elements in the array are in order. String[] array = (String[])set.toArray(new String[set.size()]);
e359. 对数组进行排序
int[] intArray = new int[] {4, 1, 3, -23};
Arrays.sort(intArray);
// [-23, 1, 3, 4]
String[] strArray = new String[] {"z", "a", "C"};
Arrays.sort(strArray);
// [C, a, z]
// Case-insensitive sort
Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
// [a, C, z]
// Reverse-order sort
Arrays.sort(strArray, Collections.reverseOrder());
// [z, a, C]
// Case-insensitive reverse-order sort
Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
Collections.reverse(Arrays.asList(strArray));
// [z, C, a]
e360. 在一个排序数组中查找一个元素
// Create an array with an ordered list of strings
String[] sortedArray = new String[]{"ant", "bat", "cat", "dog"};
// Search for the word "cat"
int index = Arrays.binarySearch(sortedArray, "cat"); // 2
// Search for a non-existent element
index = Arrays.binarySearch(sortedArray, "cow"); // -4
This example also works if the element is a primitive type.
// Create an array with an ordered list of numbers int[] sortedIntArray = new int[]{1, 2, 3, 5, 7}; // Search for 6 index = Arrays.binarySearch(sortedIntArray, 6); // -5
A negative return value indicates that the element is not in the list. However, the actual return value can be used to determine where that non-existent element should be inserted in the list if that were desired; see e361 在一个排序数组中插入元素.
e1077. 在一个排序数组中插入元素
This example demonstrates how to determine the index at which an element should be inserted into a sorted array. Although binarySearch()
is used to locate existent elements, it can also be used to determine the insert index for non-existent elements. Specifically, the insertion index is computed in the following way: insert-index = (-return-value)-1
// Create anarray with an ordered list of items String[] sortedArray = new String[]{"ant", "bat", "cat", "dog"}; // Search for a non-existent item and then insert it int index = Arrays.binarySearch(sortedArray, "cow"); if (index < 0) { // Compute the insert index int insertIndex = -index-1; // Insert the new item into sortedArray. The example here creates // a new larger array to hold the new item. String[] newSortedArray = new String[sortedArray.length+1]; System.arraycopy(sortedArray, 0, newSortedArray, 0, insertIndex); System.arraycopy(sortedArray, insertIndex, newSortedArray, insertIndex+1, sortedArray.length-insertIndex); newSortedArray[insertIndex] = "cow"; sortedArray = newSortedArray; }
e361. 在一个排序列表中查找一个元素
// Create a list with an ordered list of strings
List sortedList = new LinkedList();
sortedList.addAll(Arrays.asList(new String[]{"ant", "bat", "cat", "dog"}));
// Search for the word "cat"
int index = Collections.binarySearch(sortedList, "cat"); // 2
// Search for a non-existent element
index = Collections.binarySearch(sortedList, "cow"); // -4
A negative return value indicates that the element is not in the list. However, the actual return value can be used to determine where that non-existent element should be inserted in the list if that were desired; see e363 在一个排序列表中插入元素.
e362. 在一个排序列表中插入元素
This example demonstrates how to determine the index at which an element should be inserted into a sorted list. Although binarySearch()
is used to locate existent elements, it can also be used to determine the insert index for non-existent elements. Specifically, the insertion index is computed in the following way: insert-index = (-return-value)-1
// Create a list with an ordered list of items List sortedList = new LinkedList(); sortedList.addAll(Arrays.asList(new String[]{"ant", "bat", "cat", "dog"})); // Search for the non-existent item int index = Collections.binarySearch(sortedList, "cow"); // -4 // Add the non-existent item to the list if (index < 0) { sortedList.add(-index-1, "cow"); }
Bits
--------------------------------------------------------------------------------
e363. 对一个位指针进行位操作
The BitSet
class implements a bit-vector of an arbitrary size. It automatically grows dynamically. This example demonstrates how to create and use a BitSet
.
The BigInteger
class also support bitwise operations (see e129 对Big Integer进行位操作). However, a BigInteger
object is immutable where a BitSet
is mutable.
// Create the bitset BitSet bits = new BitSet(); // Set a bit on bits.set(2); // 100 = decimal 4 // Retrieving the value of a bit boolean b = bits.get(0); // false b = bits.get(2); // true // Clear a bit bits.clear(1); // Setting a range of bits BitSet bits2 = new BitSet(); bits2.set(1, 4); // 1110 // And'ing two bitsets bits.and(bits2); // 0100 // Xor'ing two bitsets bits.xor(bits2); // 1010 // Flip all bits in the bitset bits.flip(0, bits.length()); // 0101 // Andnot'ing two bitsets bits.andNot(bits2); // 0001 // Or'ing two bitsets bits.or(bits2); // 1111
e364. 在BitSet和字节数组之间进行转换
There are no default methods for converting a BitSet
to and from a byte array. This example implements two methods to do the conversion. These methods make it possible to easily work with both BitSet
and BigInteger
and take advantage of their capabilities when needed.
// Returns a bitset containing the values in bytes. // The byte-ordering of bytes must be big-endian which means the most significant bit is in element 0. public static BitSet fromByteArray(byte[] bytes) { BitSet bits = new BitSet(); for (int i=0; i<bytes.length*8; i++) { if ((bytes[bytes.length-i/8-1]&(1<<(i%8))) > 0) { bits.set(i); } } return bits; } // Returns a byte array of at least length 1. // The most significant bit in the result is guaranteed not to be a 1 // (since BitSet does not support sign extension). // The byte-ordering of the result is big-endian which means the most significant bit is in element 0. // The bit at index 0 of the bit set is assumed to be the least significant bit. public static byte[] toByteArray(BitSet bits) { byte[] bytes = new byte[bits.length()/8+1]; for (int i=0; i<bits.length(); i++) { if (bits.get(i)) { bytes[bytes.length-i/8-1] |= 1<<(i%8); } } return bytes; }
Property Files
--------------------------------------------------------------------------------
e365. 读取和写入一个属性文件
// Read properties file.
Properties properties = new Properties();
try {
properties.load(new FileInputStream("filename.properties"));
} catch (IOException e) {
}
// Write properties file.
try {
properties.store(new FileOutputStream("filename.properties"), null);
} catch (IOException e) {
}
Here is an example of the contents of a properties file:
# a comment ! a comment a = a string b = a string with escape sequences \t \n \r \\ \" \' \ (space) \u0123 c = a string with a continuation line \ continuation line d.e.f = another string
e366. 获取并设置属性
String string = properties.getProperty("a.b");
properties.setProperty("a.b", "new value");
Timers
--------------------------------------------------------------------------------
e367. 调度一个计时器任务,使其在特定时间执行
int numberOfMillisecondsInTheFuture = 10000; // 10 sec
Date timeToRun = new Date(System.currentTimeMillis()+numberOfMillisecondsInTheFuture);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
// Task here ...
}
}, timeToRun);
e368. 调度一个计时器任务,让它重复执行
int delay = 5000; // delay for 5 sec.
int period = 1000; // repeat every sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
// Task here ...
}
}, delay, period);
Time
--------------------------------------------------------------------------------
e369. 获取当前时间
Calendar cal = new GregorianCalendar();
// Get the components of the time
int hour12 = cal.get(Calendar.HOUR); // 0..11
int hour24 = cal.get(Calendar.HOUR_OF_DAY); // 0..23
int min = cal.get(Calendar.MINUTE); // 0..59
int sec = cal.get(Calendar.SECOND); // 0..59
int ms = cal.get(Calendar.MILLISECOND); // 0..999
int ampm = cal.get(Calendar.AM_PM); // 0=AM, 1=PM
e370. 获取另一个时区的当前时间
// Get the current time in Hong Kong
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("Hongkong"));
int hour12 = cal.get(Calendar.HOUR); // 0..11
int minutes = cal.get(Calendar.MINUTE); // 0..59
int seconds = cal.get(Calendar.SECOND); // 0..59
boolean am = cal.get(Calendar.AM_PM) == Calendar.AM;
// Get the current hour-of-day at GMT
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
int hour24 = cal.get(Calendar.HOUR_OF_DAY); // 0..23
// Get the current local hour-of-day
cal.setTimeZone(TimeZone.getDefault());
hour24 = cal.get(Calendar.HOUR_OF_DAY); // 0..23
e371. 检索所有可用时区的信息
This example lists all time zones known by the JDK.
Date today = new Date(); // Get all time zone ids String[] zoneIds = TimeZone.getAvailableIDs(); // View every time zone for (int i=0; i<zoneIds.length; i++) { // Get time zone by time zone id TimeZone tz = TimeZone.getTimeZone(zoneIds[i]); // Get the display name String shortName = tz.getDisplayName(tz.inDaylightTime(today), TimeZone.SHORT); String longName = tz.getDisplayName(tz.inDaylightTime(today), TimeZone.LONG); // Get the number of hours from GMT int rawOffset = tz.getRawOffset(); int hour = rawOffset / (60*60*1000); int min = Math.abs(rawOffset / (60*1000)) % 60; // Does the time zone have a daylight savings time period? boolean hasDST = tz.useDaylightTime(); // Is the time zone currently in a daylight savings time? boolean inDST = tz.inDaylightTime(today); }
Here's a few time zone entries:
Id, Short Name, Long Name, Hour:Time from GMT ACT, CST, Central Standard Time (Northern Territory) 9:30 AET, EST, Eastern Summer Time (New South Wales) 10:0 AGT, ART, Argentine Time -3:0 ART, EET, Eastern European Time 2:0 AST, AKST, Alaska Standard Time -9:0 Africa/Abidjan, GMT, Greenwich Mean Time 0:0 Africa/Accra, GMT, Greenwich Mean Time 0:0 Africa/Addis_Ababa, EAT, Eastern African Time 3:0 Africa/Algiers, CET, Central European Time 1:0 Africa/Asmera, EAT, Eastern African Time 3:0 Africa/Bamako, GMT, Greenwich Mean Time 0:0 Africa/Bangui, WAT, Western African Time 1:0
e372. 在时区之间进行时间转换
There is a convenient setTimeZone()
method in the Calendar
object. However, it doesn't always return the correct results when used after a calendar field is set. This example demonstrates a more reliable way to convert a specific time from one time zone to another. It involves creating two Calendar
instances and transfering the UTC (Coordinate Universal Time) from one to the other. The UTC is a representation of time and date that is independent of time zones.
// Given a local time of 10am, get the time in Japan // Create a Calendar object with the local time zone Calendar local = new GregorianCalendar(); local.set(Calendar.HOUR_OF_DAY, 10); // 0..23 local.set(Calendar.MINUTE, 0); local.set(Calendar.SECOND, 0); // Create an instance using Japan's time zone and set it with the local UTC Calendar japanCal = new GregorianCalendar(TimeZone.getTimeZone("Japan")); japanCal.setTimeInMillis(local.getTimeInMillis()); // Get the foreign time int hour = japanCal.get(Calendar.HOUR); // 3 int minutes = japanCal.get(Calendar.MINUTE); // 0 int seconds = japanCal.get(Calendar.SECOND); // 0 boolean am = japanCal.get(Calendar.AM_PM) == Calendar.AM; //true // Given a time of 10am in Japan, get the local time japanCal = new GregorianCalendar(TimeZone.getTimeZone("Japan")); japanCal.set(Calendar.HOUR_OF_DAY, 10); // 0..23 japanCal.set(Calendar.MINUTE, 0); japanCal.set(Calendar.SECOND, 0); // Create a Calendar object with the local time zone and set // the UTC from japanCal local = new GregorianCalendar(); local.setTimeInMillis(japanCal.getTimeInMillis()); // Get the time in the local time zone hour = local.get(Calendar.HOUR); // 5 minutes = local.get(Calendar.MINUTE); // 0 seconds = local.get(Calendar.SECOND); // 0 am = local.get(Calendar.AM_PM) == Calendar.AM; // false
Dates
--------------------------------------------------------------------------------
e373. 获取当前日期
Calendar cal = new GregorianCalendar();
// Get the components of the date
int era = cal.get(Calendar.ERA); // 0=BC, 1=AD
int year = cal.get(Calendar.YEAR); // 2002
int month = cal.get(Calendar.MONTH); // 0=Jan, 1=Feb, ...
int day = cal.get(Calendar.DAY_OF_MONTH); // 1...
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); // 1=Sunday, 2=Monday, ...
e374. 为特定日期建立一个Date对象
Calendar xmas = new GregorianCalendar(1998, Calendar.DECEMBER, 25);
Date date = xmas.getTime();
e375. 确定一个月当中的天数
This example uses the Calendar
class to determine the number of days in the month of a particular year.
// Create a calendar object of the desired month Calendar cal = new GregorianCalendar(1999, Calendar.FEBRUARY, 1); // Get the number of days in that month int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH); // 28