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

📄 treemapdemo2.java

📁 java2参考大全上的例子的源码和自己的理解.
💻 JAVA
字号:
package untitled3映射是按姓进行排序;

/**
 对应一个更实际的例子,下面的例子是用TreeMap程序实现前面介绍的存储账目资产
 平衡表例子的程序。在前面介绍的程序中,账目是按名进行排序的,但程序是以按照名字
 进行排序开始的。下面的程序按姓对账目进行排序。为了实现这种功能,程序使用了比较
 函数来比较每一个账目下姓的排序。得到的映射是按姓进行排序的。

 比较函数类TComp比较两个包含姓和名的字符串。它首先比较姓。具体是这样做的,
它首先寻找每一个字符串中最后一个空格的下标,然后比较从这个位置开始的每一个元素
的子字符串。当两个字符串中姓完全相等时,它再比较两个名。这样就形成了一个先按姓
进行排序,在姓相同的情况下,再按名字进行排序的树型映射。通过程序的输出中Ralph
Smith出现在Tom Smith之前的结果可以看到这一点。

 Jane Baker: 1378.0
John Doe: 3434.34
Todd Hall: 99.22
Ralph Smith: -19.08
Tom Smith: 123.22
*/

// Use a comparator to sort accounts by last name.
import java.util.*;

// Compare last whole words in two strings.
class TComp
    implements Comparator {
  public int compare(Object a, Object b) {
    int i, j, k;
    String aStr, bStr;

    aStr = (String) a;
    bStr = (String) b;

    // find index of beginning of last name
    i = aStr.lastIndexOf(' ');
    j = bStr.lastIndexOf(' ');

    k = aStr.substring(i).compareTo(bStr.substring(j));
    if (k == 0) { // last names match, check entire name
      return aStr.compareTo(bStr);
    }
    else {
      return k;
    }
  }

  // no need to override equals
}

class TreeMapDemo2 {
  public static void main(String args[]) {
    // Create a tree map
    TreeMap tm = new TreeMap(new TComp());

    // Put elements to the map
    tm.put("John Doe", new Double(3434.34));
    tm.put("Tom Smith", new Double(123.22));
    tm.put("Jane Baker", new Double(1378.00));
    tm.put("Todd Hall", new Double(99.22));
    tm.put("Ralph Smith", new Double( -19.08));

    // Get a set of the entries
    Set set = tm.entrySet();

    // Get an iterator
    Iterator itr = set.iterator();

    // Display elements
    while (itr.hasNext()) {
      Map.Entry me = (Map.Entry) itr.next();
      System.out.print(me.getKey() + ": ");
      System.out.println(me.getValue());
    }
    System.out.println();

    // Deposit 1000 into John Doe's account
    double balance = ( (Double) tm.get("John Doe")).doubleValue();
    tm.put("John Doe", new Double(balance + 1000));
    tm.get("John Doe");
  }
}

⌨️ 快捷键说明

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