JAVA与面向对象编程

Download Report

Transcript JAVA与面向对象编程

Java语言程序设计
马皓
[email protected]
1
集合操作
 对数组对象的操作(Arrays)
 对象集合(Set)
 对象列表(List)
 对象映射(Map)
 对对象数组的操作(Collections)
 枚举(Enumeration)和迭代(Iterator)
 小结
2
对数组对象的操作(Arrays)
 java.util.Arrays类
 This class contains various methods for
manipulating arrays
 排序(sorting)
 搜索(searching)
 填充(filling)
3
对数组对象的操作(Arrays)
boolean[], char[], byte[], short[], int[], long[], double[], float[]
Object[]

全部是静态方法





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.
4
对数组对象的操作(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));
}
}
5
集合操作
 对数组对象的操作(Arrays)
 对象集合(Set)
 对象列表(List)
 对象映射(Map)
 对对象数组的操作(Collections)
 枚举(Enumeration)和迭代(Iterator)
 小结
6
对象集合(Set)
 数学上“集合”概念的抽象,无序
 A Set is a collection that cannot
contain duplicate elements.
 集合与元素
 集合之间
 无序集合和有序集合
7
对象集合(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.
8
D:\java FindDups1 i came i saw i left
Duplicate: i
Duplicate: i
4 distinct
words: [came,
left, saw, i]
java.util.HashSet
implement
java.util.Set
对象集合(Set)

 无序集合
D:\
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);
}
}
9
对象集合(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.
10
D:\java FindDups2 i came i saw i left
Unique words: [came, left, saw]
Duplicate words: [i]
对象集合(Set)
 java.util.HashSet implement java.util.Set
D:\
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);
}
}
11
import java.util.*;
public class SetDemo3 {
public static void main(String args[]) {
boolean b;
 SetHashSet(无序集合)
s = new HashSet();
b = s.add("string1");
System.out.println("string1 add returns
b = s.add("string2");
System.out.println("string2 add returns
b = s.add("string3");
System.out.println("string3 add returns
b = s.add("string1");
System.out.println("string1 add returns
b = s.add("string2");
System.out.println("string2 add returns
Iterator i = s.iterator();
while (i.hasNext())
System.out.println(i.next());
}
}
对象集合(Set)
D:\java SetDemo3
string1 add returns
string2 add returns
string3 add returns
string1 add returns
string2 add returns
" + b); string3
string1
" + b); string2
true
true
true
false
false
" + b); D:\
" + b);
java.util.Iterator
" + b); 迭代器(interface)
•轮循
无序输出
12
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)
有序集合
13
import java.util.*;
D:\java SetDemo4
public class SetDemo4 {
string1 add returns true
public static void main(String args[]) {
string2 add returns true
b;
string3 add returns true
 boolean
java.util.TreeSet
implement java.util.SortedSet
Set s = new TreeSet();
string1 add returns false
b = s.add("string1");
string2 add returns false
System.out.println("string1 add returns " + b); string1
b = s.add("string2");
string2
System.out.println("string2 add returns " + b); string3
b = s.add("string3");
System.out.println("string3 add returns " + b); D:\
b = s.add("string1");
System.out.println("string1 add returns " + b);
java.util.Iterator
b = s.add("string2");
System.out.println("string2 add returns " + b); 迭代器(interface)
•轮循
Iterator i = s.iterator();
while (i.hasNext())
System.out.println(i.next());
有序输出(自然顺序)
}
14
}
对象集合(Set)
对象集合(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:\
15
D:\java SetDemo6
Exception in thread "main" java.lang.ClassCastException
对象集合(Set)
D:\ a SortedSet, add two objects to the set;
create
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.
16
集合操作
 对数组对象的操作(Arrays)
 对象集合(Set)
 对象列表(List)
 对象映射(Map)
 对对象数组的操作(Collections)
 枚举(Enumeration)和迭代(Iterator)
 小结
17
对象列表(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.
 方法操作
 列表与元素
 列表之间
18
对象列表(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.
19
对象列表(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.
20
对象列表(List)

D:\java ListDemo1
java.util.ArrayList implements java.util.List
1*1=1
2*2=4
import java.util.*;
3*3=9
public class ListDemo1 {
public static void main(String args[]) { 4 * 4 = 16
5 * 5 = 25
List list = new ArrayList();
6 * 6 = 36
for (int i = 1; i <= 10; i++)
list.add(i + " * " + i + " = " + i * i);7 * 7 = 49
8 * 8 = 64
Iterator iter = list.iterator();
9 * 9 = 81
while (iter.hasNext())
10 * 10 = 100
System.out.println(iter.next());
}
D:\
}
21
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 java.util. AbstractSequentialList
(class)
(class)
java.util.LinkedList
(class)
22
集合操作
 对数组对象的操作(Arrays)
 对象集合(Set)
 对象列表(List)
 对象映射(Map)
 对对象数组的操作(Collections)
 枚举(Enumeration)和迭代(Iterator)
 小结
23
对象映射(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.
Map
Key 1 (键)
Value 1 (值)
Entry 1
Key 2 (键)
Value 2 (值)
Entry 2
Key n (键)
Value n (值)
Entry n
24
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)
25
对象映射(Map)

java.uitl.Map接口
public interface Entry {
Object getKey();
Object getValue();
Object setValue(Object value);
}
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();
}
26
对象映射(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)
27
对象映射(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());
}
}
}
28
集合操作
 对数组对象的操作(Arrays)
 对象集合(Set)
 对象列表(List)
 对象映射(Map)
 对对象数组的操作(Collections)
 枚举(Enumeration)和迭代(Iterator)
 小结
29
对对象数组的操作(Collections)


java.util.Collections类
仅仅包含静态方法

对列表(List)的操作



最大/最小
同步处理



查询(binary Search)/拷贝(copy)/填充(fill)
洗牌(shuffle)/倒转(reverse)/排序(sort)/交换(swap)
对集合类(Collection)的操作


可类比于java.util.Arrays类
集合类(Collection)/列表(List)
映射图(Map)/集合(Set)
不可修改(只读)处理


集合类(Collection)/列表(List)
映射图(Map)/集合(Set)
30
interface java.util.Comparator
import java.util.*;
• public int compare(Object o1, Object o2)
class MySort implements Comparator{
• public boolean equals(Object obj)
对对象数组的操作(Collections)
public int compare(Object o1, Object o2)
{
import java.util.*;
 class
利用Collections类排序(指定排序方法)
public
SortDemo {
String s1 = (String)o1;
public static void main(String args[]) { String s2 = (String)o2;
List list = new ArrayList();
return s1.compareToIgnoreCase(s2);
}
list.add(“abc”);
}
list.add(“DEF”);
class Collections
list.add(“ghi”);
• public static void sort(List list)
Sorts the specified list into ascending order,
Collections.sort(list);
Iterator iter = list.iterator(); according to the natural ordering of its elements.
while(iter.hasNext())
System.out.println(iter.next());
Collections.sort(list, new MySort());
iter = list.iterator();
class Collections
while(iter.hasNext())
• public static void sort(List list, Comparator c)
System.out.println(iter.next());
Sorts the specified list according to the order
}
}
Induced by the specified comparator.
31
集合操作
 对数组对象的操作(Arrays)
 对象集合(Set)
 对象列表(List)
 对象映射(Map)
 对对象数组的操作(Collections)
 枚举(Enumeration)和迭代(Iterator)
 小结
32
枚举 (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());
}
33
枚举 (Enumeration)

提供枚举方法的类及方法

java.util.Hashtable 类



java.util.Vector 类



public Enumeration elements()
public Enumeration keys()
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
34
迭代 (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();
}
35
集合操作
 对数组对象的操作(Arrays)
 对象集合(Set)
 对象列表(List)
 对象映射(Map)
 对对象数组的操作(Collections)
 枚举(Enumeration)和迭代(Iterator)
 小结
36
小结

接口的层次关系
37
一般用途
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.
38
一般用途
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) ).
39
为什么用对象集操作






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).
40
遗留实现 (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."
41
遗留实现 (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.
42
结束 !
43