免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 969 | 回复: 0
打印 上一主题 下一主题

[ZZ]java.util示例代码大全 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-05-12 14:04 |只看该作者 |倒序浏览


java.util示例代码大全
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 are Integer objects and values are String objects. Map map = new HashMap();
   
    map.put(1, "first");
    map.put(2, "second");
    // map.put(1, 2);      
A 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 numMap = new HashMap();
   
    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 urlMap = new HashMap();
    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 "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 "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 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
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
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
   
    // Try month in a leap year
    cal = new GregorianCalendar(2000, Calendar.FEBRUARY, 1);
    days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);     // 29
e376.
日期比较
Calendar xmas = new GregorianCalendar(1998, Calendar.DECEMBER, 25);
   
    Calendar newyears = new GregorianCalendar(1999, Calendar.JANUARY, 1);
   
    // Determine which is earlier
    boolean b = xmas.after(newyears);            // false
    b = xmas.before(newyears);                   // true
   
   
    // Get difference in milliseconds
    long diffMillis = newyears.getTimeInMillis()-xmas.getTimeInMillis();
   
    // Get difference in seconds
    long diffSecs = diffMillis/(1000);           // 604800
   
    // Get difference in minutes
    long diffMins = diffMillis/(60*1000);        // 10080
   
    // Get difference in hours
    long diffHours = diffMillis/(60*60*1000);    // 168
   
    // Get difference in days
    long diffDays = diffMillis/(24*60*60*1000);  // 7
e377.
确定一个人的年龄
This example uses the Calendar class to compute a person's age.
// Create a calendar object with the date of birth
    Calendar dateOfBirth = new GregorianCalendar(1972, Calendar.JANUARY, 27);
   
    // Create a calendar object with today's date
    Calendar today = Calendar.getInstance();
   
    // Get age based on year
    int age = today.get(Calendar.YEAR) - dateOfBirth.get(Calendar.YEAR);
   
    // Add the tentative age to the date of birth to get this year's birthday
    dateOfBirth.add(Calendar.YEAR, age);
   
    // If this year's birthday has not happened yet, subtract one from age
    if (today.before(dateOfBirth)) {
        age--;
    }
e378.
确定某年是否是闰年
GregorianCalendar cal = new GregorianCalendar();
    boolean b = cal.isLeapYear(1998); // false
    b = cal.isLeapYear(2000);         // true
    b = cal.isLeapYear(0);            // true
e379.
确定某一天是星期几
The day-of-week is an integer value where 1 is Sunday, 2 is Monday, ..., and 7 is Saturday
Calendar xmas = new GregorianCalendar(1998, Calendar.DECEMBER, 25);
    int dayOfWeek = xmas.get(Calendar.DAY_OF_WEEK);    // 6=Friday
   
    Calendar cal = new GregorianCalendar(2003, Calendar.JANUARY, 1);
    dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);         // 4=Wednesday

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/14137/showart_685223.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP