1 / 43

Java 语言程序设计

Java 语言程序设计. 马 皓 mah@pku.edu.cn. 集合操作. 对数组对象的操作 (Arrays) 对象集合 (Set) 对象列表 (List) 对象映射 (Map) 对对象数组的操作 (Collections) 枚举 (Enumeration) 和迭代 (Iterator) 小结. 对数组对象的操作 (Arrays). java.util.Arrays 类 This class contains various methods for manipulating arrays 排序 (sorting) 搜索 (searching)

deborahtodd
Download Presentation

Java 语言程序设计

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java语言程序设计 马 皓 mah@pku.edu.cn

  2. 集合操作 • 对数组对象的操作(Arrays) • 对象集合(Set) • 对象列表(List) • 对象映射(Map) • 对对象数组的操作(Collections) • 枚举(Enumeration)和迭代(Iterator) • 小结

  3. 对数组对象的操作(Arrays) • java.util.Arrays类 • This class contains various methods for manipulating arrays • 排序(sorting) • 搜索(searching) • 填充(filling)

  4. boolean[], char[], byte[], short[], int[], long[], double[], float[] Object[] 对数组对象的操作(Arrays) • 全部是静态方法 • public static int binarySearch(byte[] a, byte key) Searches the specified array of bytes for the specified value using the binary search algorithm. • public static boolean equals(byte[] a, byte[] a2) Returns true if the two specified arrays of bytes are equal to one another. • public static void fill(byte[] a, byte val) Assigns the specified byte value to each element of the specified array of bytes. • public static void fill(byte[] a, int fromIndex, int toIndex, byte val) Assigns the specified byte value to each element of the specified range of the specified array of bytes. • public static void sort(byte[] a) Sorts the specified array of bytes into ascending numerical order.

  5. 对数组对象的操作(Arrays) import java.util.Arrays; public class ArrayDemo1 { public static void main(String args[]) { int[] a1 = new int[10]; int[] a2 = new int[10]; Arrays.fill(a1, 47); Arrays.fill(a2, 47); System.out.println(Arrays.equals(a1, a2)); a2[3]=11; a2[2]=9; System.out.println(Arrays.equals(a1, a2)); Arrays.sort(a2); System.out.println(Arrays.binarySearch(a2, 11)); } }

  6. 集合操作 • 对数组对象的操作(Arrays) • 对象集合(Set) • 对象列表(List) • 对象映射(Map) • 对对象数组的操作(Collections) • 枚举(Enumeration)和迭代(Iterator) • 小结

  7. 对象集合(Set) • 数学上“集合”概念的抽象,无序 • A Set is a collection that cannot contain duplicate elements. • 集合与元素 • 集合之间 • 无序集合和有序集合

  8. 对象集合(Set) • java.util.Set 接口 (集合与元素) • public boolean add(Object o) Adds the specified element to this set if it is not already present. • public boolean remove(Object o) Removes the specified element from this set if it is present. • public boolean contains(Object o) Returns true if this set contains the specified element. • public int size() Returns the number of elements in this set.

  9. D:\java FindDups1 i came i saw i left Duplicate: i Duplicate: i 4 distinct words: [came, left, saw, i] D:\ 对象集合(Set) • java.util.HashSet implement java.util.Set • 无序集合 import java.util.*; public class SetDemo1 { public static void main(String args[]) { Set s = new HashSet(); for (int i=0; i<args.length; i++) if (!s.add(args[i])) System.out.println("Duplicate: "+args[i]); System.out.println(s.size()+" distinct words: "+s); } }

  10. 对象集合(Set) • java.util.Set接口 (集合之间) • public boolean containsAll(Collection c) Returns true if this set contains all of the elements of the specified collection. • public boolean addAll(Collection c) Adds all of the elements in the specified collection to this set if they're not already present. • public boolean removeAll(Collection c) Removes from this set all of its elements that are contained in the specified collection. • public boolean retainAll(Collection c) Retains only the elements in this set that are contained in the specified collection.

  11. D:\java FindDups2 i came i saw i left Unique words: [came, left, saw] Duplicate words: [i] D:\ 对象集合(Set) • java.util.HashSet implement java.util.Set import java.util.*; public class SetDemo2 { public static void main(String args[]) { Set uniques = new HashSet(); Set dups = new HashSet(); for (int i=0; i<args.length; i++) if (!uniques.add(args[i])) dups.add(args[i]); uniques.removeAll(dups); System.out.println("Unique words: " + uniques); System.out.println("Duplicate words: " + dups); } }

  12. import java.util.*; public class SetDemo3 { public static void main(String args[]) { boolean b; Set s = new HashSet(); b = s.add("string1"); System.out.println("string1 add returns " + b); b = s.add("string2"); System.out.println("string2 add returns " + b); b = s.add("string3"); System.out.println("string3 add returns " + b); b = s.add("string1"); System.out.println("string1 add returns " + b); b = s.add("string2"); System.out.println("string2 add returns " + b); Iterator i = s.iterator(); while (i.hasNext()) System.out.println(i.next()); } } D:\java SetDemo3 string1 add returns true string2 add returns true string3 add returns true string1 add returns false string2 add returns false string3 string1 string2 D:\ 对象集合(Set) • HashSet(无序集合) java.util.Iterator 迭代器(interface) • 轮循 无序输出

  13. HashSet: Set implemented via a hash table TreeSet: SortedSet implemented as a tree 对象集合(Set) java.util.Set (interface) java.util.HashSet (class) java.util.SortedSet (interface) 无序集合 java.util.TreeSet (class) 有序集合

  14. import java.util.*; public class SetDemo4 { public static void main(String args[]) { boolean b; Set s = new TreeSet(); b = s.add("string1"); System.out.println("string1 add returns " + b); b = s.add("string2"); System.out.println("string2 add returns " + b); b = s.add("string3"); System.out.println("string3 add returns " + b); b = s.add("string1"); System.out.println("string1 add returns " + b); b = s.add("string2"); System.out.println("string2 add returns " + b); Iterator i = s.iterator(); while (i.hasNext()) System.out.println(i.next()); } } D:\java SetDemo4 string1 add returns true string2 add returns true string3 add returns true string1 add returns false string2 add returns false string1 string2 string3 D:\ 对象集合(Set) • java.util.TreeSet implement java.util.SortedSet java.util.Iterator 迭代器(interface) • 轮循 有序输出(自然顺序)

  15. 对象集合(Set) create a set and add two objects to it; the objects are distinct but have the same displayable string import java.util.*; public class SetDemo5 { public static void main(String args[]) { Set s = new HashSet(); s.add("37"); s.add(new Integer(37)); Iterator i = s.iterator(); while (i.hasNext()) System.out.println(i.next()); } } D:\java SetDemo5 37 37 D:\

  16. D:\java SetDemo6 Exception in thread "main" java.lang.ClassCastException D:\ 对象集合(Set) create a SortedSet, add two objects to the set; the objects are not comparable import java.util.*; public class SetDemo6 { public static void main(String args[]) { Set s = new TreeSet(); s.add("37"); s.add(new Integer(37)); Iterator i = s.iterator(); while (i.hasNext()) System.out.println(i.next()); } } • The exception is thrown because an attempt is made to order the elements of the set. A String object has no relationship to an Integer object, so the relative order of the two objects cannot be determined.

  17. 集合操作 • 对数组对象的操作(Arrays) • 对象集合(Set) • 对象列表(List) • 对象映射(Map) • 对对象数组的操作(Collections) • 枚举(Enumeration)和迭代(Iterator) • 小结

  18. 对象列表(List) • 有序对象的集合 • A List is an ordered collection (sometimes called a sequence). • Lists can contain duplicate elements. • The user can access elements by their integer index (position), and search for elements in the list. • 方法操作 • 列表与元素 • 列表之间

  19. 对象列表(List) • java.util.List 接口 (列表与元素) • public void add(int index, Object element) Inserts the specified element at the specified position in this list. • public Object remove(int index) Removes the element at the specified position in this list. • public boolean contains(Object o) Returns true if this list contains the specified element. • public int indexOf(Object o) Returns the index in this list of the first occurrence of the specified element, or -1 if this list does not contain this element.

  20. 对象列表(List) • java.util.List 接口 (列表之间) • public boolean addAll(Collection c) Appends all of the elements in the specified collection to the end of this list. • public boolean removeAll(Collection c) Removes from this list all the elements that are contained in the specified collection. • public boolean containsAll(Collection c) Returns true if this list contains all of the elements of the specified collection. • public boolean retainAll(Collection c) Retains only the elements in this list that are contained in the specified collection.

  21. 对象列表(List) D:\java ListDemo1 1 * 1 = 1 2 * 2 = 4 3 * 3 = 9 4 * 4 = 16 5 * 5 = 25 6 * 6 = 36 7 * 7 = 49 8 * 8 = 64 9 * 9 = 81 10 * 10 = 100 D:\ • java.util.ArrayList implements java.util.List import java.util.*; public class ListDemo1 { public static void main(String args[]) { List list = new ArrayList(); for (int i = 1; i <= 10; i++) list.add(i + " * " + i + " = " + i * i); Iterator iter = list.iterator(); while (iter.hasNext()) System.out.println(iter.next()); } }

  22. ArrayList: List implemented via an array LinkedList: List implemented as a linked structure 对象列表(List) java.util.List (interface) java.util.AbstractList (class) java.util.ArrayList (class) java.util. AbstractSequentialList (class) java.util.LinkedList (class)

  23. 集合操作 • 对数组对象的操作(Arrays) • 对象集合(Set) • 对象列表(List) • 对象映射(Map) • 对对象数组的操作(Collections) • 枚举(Enumeration)和迭代(Iterator) • 小结

  24. 对象映射(Map) • A Map is an object that maps keys to values • A map cannot contain duplicate keys: Each key can map to at most one value. Entry 1 Map Key 1 (键) Value 1 (值) Entry 2 Key 2 (键) Value 2 (值) Entry n Key n (键) Value n (值)

  25. HashMap: Map implemented via a hash table TreeMap: SortedMap implemented as a tree 对象映射(Map) 对象列表(List) java.util.Map (interface) java.util.AbstractMap (class) java.util.HashMap (class) java.util.TreeMap (class)

  26. 对象映射(Map) public interface Map { //基本操作 Object put(Object key, Object value); Object get(Object key); Object remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); int size(); boolean isEmpty(); // 批量操作 void putAll(Map t); void clear(); // Collection Views public Set keySet(); public Collection values(); public Set entrySet(); } • java.uitl.Map接口 public interface Entry { Object getKey(); Object getValue(); Object setValue(Object value); }

  27. 对象映射(Map) D:\java MapDemo1 if it is to be it is up to me to delegate 8 distinct words detected: {to=3, me=1, delegate=1, it=2, is=2, if=1, be=1, up=1} • java.uitl.HashMap implements java.util.Map import java.util.*; public class MapDemo1 { private static final Integer ONE = new Integer(1); public static void main(String args[]) { Map m = new HashMap(); for (int i=0; i<args.length; i++) { Integer freq = (Integer) m.get(args[i]); m.put(args[i], (freq==null ? ONE:new Integer(freq.intValue() + 1))); } System.out.println(m.size()+" distinct words detected:"); System.out.println(m); } } interface Map • public Object get(Object key) • public Object put(Object key, Object value)

  28. 对象映射(Map) • java.uitl.HashMap implements java.util.Map import java.util.*; public class MapDemo2 { public static void main(String args[]) { Map m = new HashMap(); m.put(”Mary”, ”123-4567”); m.put(”Larry”, ”234-5678”); m.put(”Mary”, ”456-7890”); Iterator iter = m.entrySet().iterator(); while (iter.hasNext()) { Map.Entry e = (Map.Entry)iter.next(); System.out.println(e.getKey() + ” ” + e.getValue()); } } }

  29. 集合操作 • 对数组对象的操作(Arrays) • 对象集合(Set) • 对象列表(List) • 对象映射(Map) • 对对象数组的操作(Collections) • 枚举(Enumeration)和迭代(Iterator) • 小结

  30. 对对象数组的操作(Collections) 可类比于java.util.Arrays类 • java.util.Collections类 • 仅仅包含静态方法 • 对列表(List)的操作 • 查询(binary Search)/拷贝(copy)/填充(fill) • 洗牌(shuffle)/倒转(reverse)/排序(sort)/交换(swap) • 对集合类(Collection)的操作 • 最大/最小 • 同步处理 • 集合类(Collection)/列表(List) • 映射图(Map)/集合(Set) • 不可修改(只读)处理 • 集合类(Collection)/列表(List) • 映射图(Map)/集合(Set)

  31. interface java.util.Comparator • public int compare(Object o1, Object o2) • public boolean equals(Object obj) import java.util.*; class MySort implements Comparator{ public int compare(Object o1, Object o2) { String s1 = (String)o1; String s2 = (String)o2; return s1.compareToIgnoreCase(s2); } } 对对象数组的操作(Collections) import java.util.*; public class SortDemo { public static void main(String args[]) { List list = new ArrayList(); list.add(“abc”); list.add(“DEF”); list.add(“ghi”); Collections.sort(list); Iterator iter = list.iterator(); while(iter.hasNext()) System.out.println(iter.next()); Collections.sort(list, new MySort()); iter = list.iterator(); while(iter.hasNext()) System.out.println(iter.next()); } } • 利用Collections类排序(指定排序方法) class Collections • public static void sort(List list) Sorts the specified list into ascending order, according to the natural ordering of its elements. class Collections • public static void sort(List list, Comparator c) Sorts the specified list according to the order Induced by the specified comparator.

  32. 集合操作 • 对数组对象的操作(Arrays) • 对象集合(Set) • 对象列表(List) • 对象映射(Map) • 对对象数组的操作(Collections) • 枚举(Enumeration)和迭代(Iterator) • 小结

  33. 枚举 (Enumeration) • java.util.Enumeration 接口 • An object that implements the Enumeration interface generates a series of elements, one at a time. • Successive calls to the nextElement method return successive elements of the series. • 两个方法 • public boolean hasMoreElements() • public Object nextElement() • 示例 for (Enumeration e = v.elements() ; e.hasMoreElements() ;) { System.out.println(e.nextElement());}

  34. 枚举 (Enumeration) • 提供枚举方法的类及方法 • java.util.Hashtable 类 • public Enumeration elements() • public Enumeration keys() • java.util.Vector 类 • public Enueration elements() • 来自 JDK 1.0 • 注意 • The functionality of this interface is duplicated by the Iterator interface. In addition, Iterator adds an optional remove operation, and has shorter method names. New implementations should consider using Iterator in preference to Enumeration

  35. 迭代 (Iterator) • java.util.Iterator接口 • 来自JDK 1.2 • 三个方法 • public boolean hasNext() • public Object next() • public void remove() • 示例 static void filter(Collection c) { for (Iterator i = c.iterator(); i.hasNext(); ) if (!cond(i.next())) i.remove(); }

  36. 集合操作 • 对数组对象的操作(Arrays) • 对象集合(Set) • 对象列表(List) • 对象映射(Map) • 对对象数组的操作(Collections) • 枚举(Enumeration)和迭代(Iterator) • 小结

  37. 小结 • 接口的层次关系

  38. 一般用途 • java.util.HashSet 类 • Hash table implementation of the Set interface. The best all-around implementation of the Set interface. • java.util.TreeSet 类 • Red-black tree implementation of the SortedSet interface. • java.util.LinkedHashSet 类 • Hash table and linked list implementation of the Set interface. An insertion-ordered Set implementation that runs nearly as fast as HashSet. • java.util.ArrayList 类 • Resizable-array implementation of the List interface. (Essentially an unsynchronized Vector.) The best all-around implementation of the List interface.

  39. 一般用途 • java.util.LinkedList 类 • Doubly-linked list implementation of the List interface. May provide better performance than the ArrayList implementation if elements are frequently inserted or deleted within the list. Useful for queues and double-ended queues (deques). • java.util.HashMap 类 • Hash table implementation of the Map interface. (Essentially an unsynchronized Hashtable that supports null keys and values.) The best all-around implementation of the Map interface. • java.util.TreeMap 类 • Red-black tree implementation of the SortedMap interface. • java.util.LinkedHashMap 类 • Hash table and linked list implementation of the Map interface. An insertion-ordered Map implementation that runs nearly as fast as HashMap. Also useful for building caches (see removeEldestEntry(Map.Entry) ).

  40. 为什么用对象集操作 • Reduced programming effort. • Support for software reuse, in that data structures conforming to the collection interfaces are reusable in a wide variety of contexts and applications. • Easier to design with APIs. • Easier to pass collections between unrelated APIs. • Increased program speed. • Increased program quality (fewer bugs, easier maintenance).

  41. 遗留实现 (Legacy Implementation) • Older collection classes have been retrofitted to implement the collection interfaces. • java.util.Vector (矢量数组) • Synchronized resizable-array implementation of the List interface with additional "legacy methods." • java.util.Hashtable (哈希表) • Synchronized hash table implementation of the Map interface that does not allow null keys or values, with additional "legacy methods."

  42. 遗留实现 (Legacy Implementation) • 一些注意 • Vector and Hashtable (legacy collections) are synchronized, whereas new collections (like ArrayList and HashMap) are unsynchronized, and must be "wrapped" via Collections.SynchronizedList or Collections.synchronizedMap if synchronization is desired.

  43. 结束 !

More Related