⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chap17.code

📁 Eclipse+Web开发从入门到精通 These files contain all of the code listings in Java: The Complete Referenc
💻 CODE
📖 第 1 页 / 共 2 页
字号:
    ll.add(8);  
      
    // Create a reverse order comparator. 
    Comparator<Integer> r = Collections.reverseOrder();  
  
    // Sort list by using the comparator. 
    Collections.sort(ll, r);  
  
    System.out.print("List sorted in reverse: ");      
    for(int i : ll) 
      System.out.print(i+ " ");  
 
    System.out.println();  
  
    // Shuffle list. 
    Collections.shuffle(ll);  
  
    // Display randomized list. 
    System.out.print("List shuffled: ");      
    for(int i : ll) 
      System.out.print(i + " ");  
 
    System.out.println();  
  
    System.out.println("Minimum: " + Collections.min(ll));      
    System.out.println("Maximum: " + Collections.max(ll));          
  }  
}


listing 14
// Demonstrate Arrays  
import java.util.*;  
  
class ArraysDemo {  
  public static void main(String args[]) {  
  
    // Allocate and initialize array. 
    int array[] = new int[10];  
    for(int i = 0; i < 10; i++)  
      array[i] = -3 * i;  
  
    // Display, sort, and display the array. 
    System.out.print("Original contents: ");  
    display(array);  
    Arrays.sort(array);  
    System.out.print("Sorted: ");  
    display(array);  
  
    // Fill and display the array. 
    Arrays.fill(array, 2, 6, -1);  
    System.out.print("After fill(): ");  
    display(array);  
  
    // Sort and display the array. 
    Arrays.sort(array);  
    System.out.print("After sorting again: ");  
    display(array);  
  
    // Binary search for -9. 
    System.out.print("The value -9 is at location ");  
    int index =   
      Arrays.binarySearch(array, -9);  
 
    System.out.println(index);  
  }  
  
  static void display(int array[]) {  
    for(int i: array) 
      System.out.print(i + " ");  
 
    System.out.println();  
  }  
}

listing 15
// Pre-generics example that uses a collection. 
import java.util.*; 
 
class OldStyle {  
  public static void main(String args[]) { 
    ArrayList list = new ArrayList(); 
 
    // These lines store strings, but any type of object 
    // can be stored.  In old-style code, there is no  
    // convenient way restrict the type of objects stored 
    // in a collection 
    list.add("one"); 
    list.add("two"); 
    list.add("three"); 
    list.add("four"); 
 
    Iterator itr = list.iterator(); 
    while(itr.hasNext()) { 
 
      // To retrieve an element, an explicit type cast is needed 
      // because the collection stores only Object. 
      String str = (String) itr.next(); // explicit cast needed here. 
 
      System.out.println(str + " is " + str.length() + " chars long."); 
    } 
  }  
}

listing 16
// Modern, generics version. 
import java.util.*; 
 
class NewStyle {  
  public static void main(String args[]) { 
 
    // Now, list holds references of type String. 
    ArrayList<String> list = new ArrayList<String>(); 
 
    list.add("one"); 
    list.add("two"); 
    list.add("three"); 
    list.add("four"); 
 
    // Notice that Iterator is also generic. 
    Iterator<String> itr = list.iterator(); 
 
    // The following statement will now cause a compile-time eror. 
//    Iterator<Integer> itr = list.iterator(); // Error! 
 
    while(itr.hasNext()) { 
      String str = itr.next(); // no cast needed 
 
      // Now, the following line is a compile-time, 
      // rather than runtime, error. 
//    Integer i = itr.next(); // this won't compile 
 
      System.out.println(str + " is " + str.length() + " chars long."); 
    } 
  }  
}

listing 17
// Demonstrate various Vector operations. 
import java.util.*; 
 
class VectorDemo { 
  public static void main(String args[]) { 
 
    // initial size is 3, increment is 2 
    Vector<Integer> v = new Vector<Integer>(3, 2); 
 
    System.out.println("Initial size: " + v.size()); 
    System.out.println("Initial capacity: " + 
                       v.capacity()); 
 
    v.addElement(1); 
    v.addElement(2); 
    v.addElement(3); 
    v.addElement(4); 
 
    System.out.println("Capacity after four additions: " + 
                       v.capacity()); 
    v.addElement(5); 
    System.out.println("Current capacity: " + 
                       v.capacity()); 
    v.addElement(6); 
    v.addElement(7); 
 
    System.out.println("Current capacity: " + 
                       v.capacity()); 
    v.addElement(9); 
    v.addElement(10); 
 
    System.out.println("Current capacity: " + 
                       v.capacity()); 
    v.addElement(11); 
    v.addElement(12); 
 
 
    System.out.println("First element: " + v.firstElement()); 
    System.out.println("Last element: " + v.lastElement()); 
 
    if(v.contains(3)) 
      System.out.println("Vector contains 3."); 
 
    // Enumerate the elements in the vector. 
    Enumeration vEnum = v.elements(); 
 
    System.out.println("\nElements in vector:"); 
    while(vEnum.hasMoreElements()) 
      System.out.print(vEnum.nextElement() + " "); 
    System.out.println(); 
  } 
}

listing 18
// Use an iterator to display contents. 
Iterator<Integer> vItr = v.iterator(); 
 
System.out.println("\nElements in vector:"); 
while(vItr.hasNext())  
  System.out.print(vItr.next() + " "); 
System.out.println();

listing 19
// Use an enhanced for loop to display contents.   
System.out.println("\nElements in vector:");  
for(int i : v) 
  System.out.print(i + " ");  
 
System.out.println();

listing 20
// Demonstrate the Stack class. 
import java.util.*; 
  
class StackDemo { 
  static void showpush(Stack<Integer> st, int a) { 
    st.push(a); 
    System.out.println("push(" + a + ")"); 
    System.out.println("stack: " + st); 
  } 
 
  static void showpop(Stack<Integer> st) { 
    System.out.print("pop -> "); 
    Integer a = st.pop(); 
    System.out.println(a); 
    System.out.println("stack: " + st); 
  } 
 
  public static void main(String args[]) { 
    Stack<Integer> st = new Stack<Integer>(); 
 
    System.out.println("stack: " + st); 
    showpush(st, 42); 
    showpush(st, 66); 
    showpush(st, 99); 
    showpop(st); 
    showpop(st); 
    showpop(st); 
 
    try { 
      showpop(st); 
    } catch (EmptyStackException e) { 
      System.out.println("empty stack"); 
    } 
  } 
}

listing 21
// Demonstrate a Hashtable. 
import java.util.*; 
  
class HTDemo { 
  public static void main(String args[]) { 
    Hashtable<String, Double> balance = 
      new Hashtable<String, Double>(); 
 
    Enumeration<String> names; 
    String str; 
    double bal; 
 
    balance.put("John Doe", 3434.34); 
    balance.put("Tom Smith", 123.22); 
    balance.put("Jane Baker", 1378.00); 
    balance.put("Tod Hall", 99.22); 
    balance.put("Ralph Smith", -19.08); 
 
    // Show all balances in hashtable. 
    names = balance.keys(); 
    while(names.hasMoreElements()) { 
      str = names.nextElement(); 
      System.out.println(str + ": " + 
                         balance.get(str)); 
    } 
 
    System.out.println(); 
 
    // Deposit 1,000 into John Doe's account. 
    bal = balance.get("John Doe"); 
    balance.put("John Doe", bal+1000); 
    System.out.println("John Doe's new balance: " + 
                       balance.get("John Doe")); 
  } 
}

listing 22
// Use iterators with a Hashtable. 
import java.util.*; 
 
class HTDemo2 { 
  public static void main(String args[]) { 
    Hashtable<String, Double> balance = 
      new Hashtable<String, Double>(); 
 
    String str; 
    double bal; 
 
    balance.put("John Doe", 3434.34); 
    balance.put("Tom Smith", 123.22); 
    balance.put("Jane Baker", 1378.00); 
    balance.put("Tod Hall", 99.22); 
    balance.put("Ralph Smith", -19.08); 
 
    // Show all balances in hashtable. 
    // First, get a set view of the keys. 
    Set<String> set = balance.keySet(); 
 
    // Get an iterator. 
    Iterator<String> itr = set.iterator(); 
    while(itr.hasNext()) { 
      str = itr.next(); 
      System.out.println(str + ": " + 
                         balance.get(str)); 
    } 
 
    System.out.println(); 
 
    // Deposit 1,000 into John Doe's account. 
    bal = balance.get("John Doe"); 
    balance.put("John Doe", bal+1000); 
    System.out.println("John Doe's new balance: " + 
                       balance.get("John Doe")); 
  } 
}

listing 23
// Demonstrate a Property list.  
import java.util.*;  
   
class PropDemo {  
  public static void main(String args[]) {  
    Properties capitals = new Properties();  
  
    capitals.put("Illinois", "Springfield");  
    capitals.put("Missouri", "Jefferson City");  
    capitals.put("Washington", "Olympia");  
    capitals.put("California", "Sacramento");  
    capitals.put("Indiana", "Indianapolis");  
  
    // Get a set-view of the keys. 
    Set states = capitals.keySet(); 
  
    // Show all of the states and capitals. 
    for(Object name : states)  
      System.out.println("The capital of " +  
                         name + " is " +  
                         capitals.getProperty((String)name)  
                         + ".");  
  
    System.out.println();  
  
    // Look for state not in list -- specify default. 
    String str = capitals.getProperty("Florida", "Not Found");  
    System.out.println("The capital of Florida is "  
                       + str + ".");  
  }  
}

listing 24
// Use a default property list.  
import java.util.*;  
   
class PropDemoDef {  
  public static void main(String args[]) {  
    Properties defList = new Properties();  
    defList.put("Florida", "Tallahassee");  
    defList.put("Wisconsin", "Madison");  
  
    Properties capitals = new Properties(defList);  
  
    capitals.put("Illinois", "Springfield");  
    capitals.put("Missouri", "Jefferson City");  
    capitals.put("Washington", "Olympia");  
    capitals.put("California", "Sacramento");  
    capitals.put("Indiana", "Indianapolis");  
  
    // Get a set-view of the keys. 
    Set states = capitals.keySet(); 
  
    // Show all of the states and capitals. 
    for(Object name : states)  
      System.out.println("The capital of " +  
                         name + " is " +  
                         capitals.getProperty((String)name)  
                         + ".");  
  
    System.out.println();  
  
    // Florida will now be found in the default list.  
    String str = capitals.getProperty("Florida");  
    System.out.println("The capital of Florida is "  
                       + str + ".");  
  }  
}

listing 25
/* A simple telephone number database that uses 
   a property list. */ 
import java.io.*; 
import java.util.*; 
 
class Phonebook { 
  public static void main(String args[])  
    throws IOException 
  { 
    Properties ht = new Properties(); 
    BufferedReader br = 
      new BufferedReader(new InputStreamReader(System.in)); 
    String name, number; 
    FileInputStream fin = null; 
    boolean changed = false; 
 
    // Try to open phonebook.dat file. 
    try { 
      fin = new FileInputStream("phonebook.dat"); 
    } catch(FileNotFoundException e) { 
      // ignore missing file 
    } 
 
    /* If phonebook file already exists,  
       load existing telephone numbers. */ 
    try { 
      if(fin != null) { 
        ht.load(fin); 
        fin.close(); 
      } 
    } catch(IOException e) { 
      System.out.println("Error reading file."); 
    } 
 
    // Let user enter new names and numbers. 
    do { 
      System.out.println("Enter new name" +  
                         " ('quit' to stop): "); 
      name = br.readLine(); 
      if(name.equals("quit")) continue; 
 
      System.out.println("Enter number: "); 
      number = br.readLine(); 
 
      ht.put(name, number); 
      changed = true; 
    } while(!name.equals("quit")); 
 
    // If phone book data has changed, save it. 
    if(changed) { 
      FileOutputStream fout = new FileOutputStream("phonebook.dat"); 
 
      ht.store(fout, "Telephone Book"); 
      fout.close(); 
    } 
 
    // Look up numbers given a name. 
    do { 
      System.out.println("Enter name to find" + 
                         " ('quit' to quit): "); 
      name = br.readLine(); 
      if(name.equals("quit")) continue; 
 
      number = (String) ht.get(name); 
      System.out.println(number); 
    } while(!name.equals("quit")); 
  } 
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -