Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
CS 2112 Lab: Java API
13 – 15 February 2012
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
StringBuilder/StringBuffer
String Concatenation
String objects are immutable. So what happens when we try to
concatenate two Strings?
Since we can’t modify either of the two original String objects, a
new String object must be created for each concatenation. This
is inefficient when concatenating a large number of strings.
1 String str = "a" + "b" + "c" + "d";
String objects created: {a, b, c , d , ab, abc, abcd}.
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
StringBuilder/StringBuffer
Introducing StringBuilder/StringBuffer
The StringBuilder and StringBuffer classes are modifiable
versions of String. They are identical, except that StringBuffer
is thread-safe and StringBuilder is not. Both classes implement
the interface CharSequence. We can use these classes to
concatenate strings without having to create new objects.
1 StringBuilder sb = new StringBuilder ();
2 sb.append("a"). append("b"). append("c"). append("d");
3 String str = sb.toString ();
String objects created: {a, b, c , d , abcd}.
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
StringBuilder/StringBuffer
Example
1 StringBuilder sb = new StringBuilder("abc"); // "abc"
2 sb.append("a"). append (3). append(’c’); // "abca3c"
3 sb.insert(4, "12"); // "abca123c"
4 sb.replace(3, 4, "0"). delete(7, 8); // "abc0123"
5 sb.append(sb.length ()); // "abc01237"
6 sb.reverse (); // "73210 cba"
7 String str = sb.toString ();
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Math
Introduction and Example 1
Java has a default math library. It is fairly self-explanatory.
Perhaps the most commonly used of these functions would be
pow(double a, double b) which returns ab. Math has two
constants: E and PI. Furthermore, all of its fields and methods are
static. Math also has a random() function, which returns a
random double in the interval [0.0, 1.0).
1 int randInt(int lim) {
2 // returns a random integer
3 // in the interval [0, abs(lim) - 1]
4 // if lim is 0, returns 0
5
6 lim = Math.max(0, Math.abs(lim) - 1);
7 return (int) (Math.random () * lim);
8 }
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Math
Example 2
1 void euler(double x) {
2 // computes e^(ix) using Euler ’s formula:
3 // e^(ix) = cos(x) + i sin(x)
4 StringBuilder sb = new StringBuilder ();
5 sb.append(Math.cos(x));
6 double i = Math.sin(x);
7
8 if(i < 0)
9 sb.append(" - "). append(-i). append("i");
10 else
11 sb.append(" + "). append(i). append("i");
12
13 System.out.println(sb.toString ());
14 }
15 euler(Math.PI); // -1.0 + 1.2246467991473532E-16i
16 // due to rounding error
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Wrapper Classes
Introduction
For each primitive type, Java has a wrapper class which allows
treating the primitive type as an Object. Aside from providing
useful constants and functions, having wrapper classes is useful
because data structures, such as the standard Java containers,
generally only accept Objects as data values; wrapper classes
enable using these containers with primitive types. Each primitive
type has a corresponding wrapper class whose name is the full
name of the primitive, with the first letter capitalized. In addition,
there is a class Number which is the superclass of the wrapper
classes for the numeric primitives. It can be used to e.g. write a
function that accepts any numeric type.
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Wrapper Classes
Example
1 int x = Integer.parseInt("123");
2 Integer y = 777; // <-- boxing
3 long xL = y.longValue ();
4 int z = y + Integer.MAX_VALUE; // <-- integer overflow
5
6 String bool = Boolean.toString(true);
7 if(bool.equals(Boolean.TRUE.toString ()))
8 System.out.println(z); // -2147482872
9
10 x += Character.getNumericValue(’X’);
11 if(Double.isInfinite (1.0 / 0.0))
12 System.out.println(x); // 156
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Introduction and Methods
Introduction
Java handles input and output using streams. A stream is
essentially a flow of data from a source to a destination: the
source can produce more data, which is transmitted along the
stream, and the destination can read data that has been sent,
consuming it. The destination can also wait for the source to send
more data, in the event that there isn’t enough data to use.
There are four abstract classes used for this: InputStream,
OutputStream, Reader, and Writer. InputStream and
OutputStream operate at the byte level, whereas Reader and
Writer operate at the character level. All of these classes are in
the java.io package.
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Introduction and Methods
Reader/InputStream Methods
1 // skip n bytes
2 // returns the number of bytes skipped
3 long skip(long n)
4
5 // read the next byte/char
6 // returns the byte/char; -1 if end of stream
7 int read()
8
9 // read several bytes
10 // returns the # of bytes read; -1 if end of stream
11 // InputStream only
12 int read(byte[] b)
13
14 // read several chars
15 // returns the # of chars read; -1 if end of stream
16 // Reader only
17 int read(char[] c)
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Introduction and Methods
Writer/OutputStream Methods
1 // flush the output stream and write its buffer
2 void flush ()
3
4 // write a single byte/char
5 void write(int b)
6
7 // write several bytes
8 // OutputStream only
9 void write(byte[] b)
10
11 // write several chars
12 // Writer only
13 void write(char[] c)
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Introduction and Methods
Closing Streams
For all four of these classes, it is important to remember to close
the stream once the program is done with them. This releases any
resources held by the stream; failure to close could lead to resource
leaks.
It is good practice to wrap code using a stream within a
try-finally block, with code to close the stream within the
block’s finally clause. This way, even if an exception is thrown,
the program will still attempt to close the stream.
1 // close a stream , and release its resources
2 void close ()
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Introduction and Methods
Wrapping Stream Classes
In addition to the four basic stream classes, Java also provides
some convenience stream classes which wrap and add extra
functionality to the four basic stream classes. In addition, closing a
wrapper stream class will also automatically close the wrapped
stream class. Two wrapper stream classes that add some basic
functions for handling Strings are BufferedReader and
PrintWriter.
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Introduction and Methods
BufferedReader/PrintWriter Methods
1 // wraps an existing Reader
2 BufferedReader(Reader in)
3
4 // read a line
5 String readLine ()
1 // wraps an existing Writer or OutputStream
2 PrintWriter(Writer out)
3 PrintWriter(OutputStream out)
4 // writes to a file
5 PrintWriter(String fileName)
6
7 // print a String
8 void print(String s)
9 // print a String and write a newline
10 void println(String s)
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
System Streams and Examples
System Streams
Java has three special streams:
System.out System.out is a PrintStream which prints to the
standard console.
System.in System.in is an InputStream which reads from the
standard console.
System.err System.err is a PrintStream which prints to the
error console.
Unlike the normal streams, closing these special streams is usually
not a good idea, and can lead to odd behaviour.
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
System Streams and Examples
Abstraction
When declaring a variable or an argument to a function, it is best
to use the most general class available that still provides the
required functionality. This allows the details of the
implementation to be abstracted away from the code: the actual
implementation of the stream can be changed without affecting
the code, so long as the same interface is provided.
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
System Streams and Examples
Example 1
1 String str = "abcdefg";
2 Reader in = new StringReader(str);
3 try {
4 try {
5 int read;
6 while ((read = in.read ()) != -1)
7 // reads and prints one character
8 System.out.print ((char) read);
9 System.out.println ();
10 } finally {
11 // try to close even if we encounter a problem
12 in.close ();
13 }
14 } catch(IOException e) {
15 System.out.println(e.getMessage ());
16 }
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
System Streams and Examples
Example 2
1 BufferedReader in = null;
2 PrintWriter out = null;
3 try {
4 try {
5 in = new BufferedReader(new FileReader("in"));
6 out = new PrintWriter(new FileWriter("out"));
7 String read;
8 while ((read = in.readLine ()) != null)
9 out.println(read);
10 } finally {
11 if(in != null) in.close ();
12 if(out != null) out.close ();
13 }
14 } catch(IOException e) {
15 System.out.println(e.getMessage ());
16 }
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Introduction and Methods
Interfaces 1
Java provides many container implementations. First we will
introduce some of the interfaces used by the containers:
List Fairly self-explanatory; Lists are ordered and thus
their elements are always traversed in the same order.
Lists also have a get(int index) method that
allows for retrieving an element at a specific location
in the list. Duplicates are also allowed.
Map Maps are an unordered collection of key-value pairs.
Maps cannot contain multiple pairs with the same
key, but values can be duplicated. Maps have a
get(Object key) method that returns the value to
which that key is mapped, or null if the key is not
mapped to anything.
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Introduction and Methods
Interfaces 2
Set Sets are an unordered collection of objects.
Duplicates are not allowed.
Iterator Iterators provide a method to iterate over every
element in a collection. They are the most basic
method of accessing the elements of a collection.
All of these interfaces, as well as their implementations, are in the
java.util package.
In the following slides, we will list some useful methods of these
interfaces. We will use E for the type of the elements of Lists,
Sets and Iterators; we will use K, V for the type of keys and
values of Maps.
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Introduction and Methods
List Methods 1
1 // append an element
2 // always returns true
3 boolean add(E e)
4
5 // insert an element at index
6 void add(int index , E e)
7
8 // removes all elements
9 void clear ()
10
11 // returns if the object is in the list
12 boolean contains(Object o)
13
14 // returns the element at index
15 E get(int index)
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Introduction and Methods
List Methods 2
1 // returns true if list is empty
2 boolean isEmpty ()
3
4 // returns an iterator for the list
5 Iterator  iterator ()
6
7 // removes element at index
8 // returns the removed element
9 E remove(int index)
10
11 // removes object if it is in the list
12 // returns true if it was in the list
13 boolean remove(Object o)
14
15 // returns length of list
16 int size()
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Introduction and Methods
Map Methods 1
1 // removes all mappings
2 void clear ()
3
4 // returns if the element is a key in the map
5 boolean containsKey(Object key)
6
7 // returns if the element is a value in the map
8 boolean containsValue(Object value)
9
10 // returns the value associated with key
11 // returns null if key not in map
12 V get(Object key)
13
14 // returns true if map is empty
15 boolean isEmpty ()
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Introduction and Methods
Map Methods 2
1 // returns a Set of the keys in the map
2 Set  keySet ()
3
4 // adds the mapping (key , value) into the map
5 // overwrites any pre -existing mapping for key
6 // returns the overwritten value , or null if none
7 V put(K key , V value)
8
9 // removes the mapping for key , if it exists
10 // returns the previous value , or null if none
11 V remove(Object key)
12
13 // returns the # of mappings in the map
14 int size()
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Introduction and Methods
Set Methods 1
1 // add an element if it is not already in the set
2 // returns true if not already in the set
3 boolean add(E e)
4
5 // removes all elements
6 void clear ()
7
8 // returns if the object is in the set
9 boolean contains(Object o)
10
11 // returns true if set is empty
12 boolean isEmpty ()
13
14 // returns an iterator for the set
15 Iterator  iterator ()
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Introduction and Methods
Set Methods 2
1 // removes object if it is in the set
2 // returns true if it was in the set
3 boolean remove(Object o)
4
5 // returns size of set
6 int size()
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Introduction and Methods
Iterator Methods
1 // returns true if the iterator has more elements
2 boolean hasNext ()
3
4 // returns the next element in the iterator
5 E next()
6
7 // removes last returned element from the collection
8 // can only be called once per call to next()
9 // this is the only way to safely modify a collection
10 // while iterating through it
11 void remove ()
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Introduction and Methods
Collections and Arrays
Java also provides some useful static constants and methods for
use with collections in the java.util.Collections class (not to
be confused with java.util.Collection, which is a
superinterface of List and Set). Among other things,
Collections has methods for sorting, reversing, and binary
searching lists.
Similarly, java.util.Arrays has some useful static methods for
use with arrays, including sorting, binary searching, and converting
to string.
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Implementations and Examples
Implementations 1
Now we will look at some of the implementations of the above
interfaces.
ArrayList ArrayLists are essentially an
automatically-expanding array that implements the
List interface. Since the underlying data structure is
an array, it is cheap to add or remove elements from
the end, and to access elements anywhere in the list,
but expensive to insert or remove elements from the
beginning or middle of the list.
LinkedList As their name suggests, LinkedLists are linked lists
that implement the List interface. They support
cheap insertion or removal of elements from anywhere
in the list, but only support in-order traversal.
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Implementations and Examples
Implementations 2
HashMap HashMaps use a hash table to implement the Map
interface. They use Object.equals(Object o) and
Object.hashCode() to perform the hashing.
HashSet HashSets use a hash table to implement the Set
interface. They use Object.equals(Object o) and
Object.hashCode() to perform the hashing.
TreeMap TreeMaps use a tree to implement the Map interface.
Although Maps don’t have to be sorted, TreeMaps are
sorted and will iterate in order. They use
Comparable.compareTo(T o) to sort.
TreeSet TreeSets use a tree to implement the Set interface.
Although Sets don’t have to be sorted, TreeSets are
sorted and will iterate in order. They use
Comparable.compareTo(T o) to sort.
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Implementations and Examples
Abstraction
As with streams, when declaring a variable or an argument to a
function, it is best to use the most general class available that still
provides the required functionality. This allows the details of the
implementation to be abstracted away from the code: the actual
implementation of the stream can be changed without affecting
the code, so long as the same interface is provided.
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Implementations and Examples
Example 1
1 int[] list = {5, 8, 3, 6, 4, 8, 4, 0};
2 List  sorted = new ArrayList ();
3 for(Integer i : list)
4 sorted.add(i);
5
6 Collections.sort(sorted );
7
8 Iterator  iter = sorted.iterator ();
9 System.out.print("Sorted: ");
10 while(iter.hasNext ())
11 System.out.print(iter.next() + " ");
12 System.out.println ();
13
14 // Sorted: 0 3 4 4 5 6 8 8
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Implementations and Examples
Example 2
1 int[] list = {5, 8, 3, 6, 4, 8, 4, 0};
2 Set  set = new HashSet ();
3 for(Integer i : list)
4 set.add(i);
5
6 Iterator  iter = set.iterator ();
7 System.out.print("Set: ");
8 while(iter.hasNext ())
9 System.out.print(iter.next() + " ");
10 System.out.println ();
11
12 // Set: 0 3 4 5 6 8
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Implementations and Examples
Example 3
1 String [][] pairs = {{"A", "1"}, {"B", "2"},
2 {"C", "3"}};
3 Map  map =
4 new HashMap ();
5 for(String [] pair : pairs)
6 map.put(pair[0], Integer.parseInt(pair [1]));
7
8 for(int i = 0; i < pairs.length; i++)
9 System.out.println(pairs[i][0] + " --> "
10 + map.get(pairs[i][0]));
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Implementations and Examples
Concurrent Modification
If a container is modified (by adding or removing elements) while it
is being iterated through (whether by using an Iterator or by
using a for-each loop), very bad things can happen. If you’re
lucky, Java will throw a ConcurrentModificationException
when something tries to modify the container; if you’re not, then
the program will keep running and the iterator can behave
unpredictably, possibly causing failures elsewhere in the program.
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Implementations and Examples
Concurrent Modification Examples
1 int[] array = {5, 8, 3, 6, 4, 8, 4, 0};
2 List  list = new ArrayList ();
3 for(Integer i : array)
4 list.add(i);
5
6 for(Integer i : list) // should crash here
7 list.add(i);
1 int[] array = {5, 8, 3, 6, 4, 8, 4, 0};
2 List  list = new ArrayList ();
3 for(Integer i : array)
4 list.add(i);
5
6 Iterator iter = list.iterator ();
7 while(iter.hasNext ())
8 list.remove(iter.next ()); // should crash here
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Exercises
Exercise 1
Given a List of strings, construct a Map that maps integers to a
Set of strings of that length.
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Exercises
Exercise 2
Read a file containing one integer per line, then write the absolute
values of the integers into a different file, with the catch that if
multiple integers have the same absolute value, you should only
write that absolute value once. Bonus points if you write the
absolute values in increasing (or decreasing) order.
CS 2112 Lab: Java API
StringBuilder/StringBuffer Math Wrapper Classes Streams Containers Exercises
Exercises
Exercise 3
Implement a stack using a List as your underlying data structure.
CS 2112 Lab: Java API