//============================================================== // BinaryDemo.java - Search a container using Collections.binarySearch() // // Java学习源代码检索系统 Ver 1.0 20031015 免费正式版 // 版权所有: 中国IT认证实验室(www.ChinaITLab.com) // 程序制作: ChinaITLab网校教研中心 // 主页地址: www.ChinaITLab.com 中国IT认证实验室 // 论坛地址: bbs.chinaitlab.com // 电子邮件: Java@ChinaITLab.com //============================================================== import java.util.List; import java.util.Comparator; import java.util.ArrayList; import java.util.Collections; import Chart; class BinaryDemo { // Display a List container's contents public static void showContainer(List c) { for (int i = 0; i < c.size(); i++) System.out.println(c.get(i).toString()); } public static void main(String args[]) { // Construct the container ArrayList charts = new ArrayList(); // Insert some Data objects charts.add(new Chart(11013, "Morehead City Hrbr ", 12500)); charts.add(new Chart(11552, "Neuse River ", 40000)); charts.add(new Chart(11428, "Dry Tortugas ", 30000)); charts.add(new Chart(11420, "Havana to Tampa Bay", 470940)); charts.add(new Chart(25641, "Virgin Islands ", 100000)); charts.add(new Chart(26341, "Bermuda Islands ", 50000)); // Display all objects if none requested if (args.length == 0) { System.out.println("\nContainer contents:"); showContainer(charts); System.out.println("\nEnter a chart number to find"); System.out.println("ex. java BinaryDemo 11428"); } else { // Search container using Collections.binarySearch() try { // Preparations for a binarySearch(); int num = Integer.parseInt(args[0]); // Get chart number Comparator comp = Chart.byNumber(); // Create Comparator Chart key = new Chart(num, "", 0); // Create search key Collections.sort(charts, comp); // Sort container // Search the container for the key object int index = Collections.binarySearch(charts, key, comp); if (index < 0) System.out.println("Chart #" + args[0] + " not found"); else System.out.println(charts.get(index)); // Show chart } catch (NumberFormatException e) { System.out.println("Error in argument " + e.getMessage()); } } } }
最近下载更多
zhaoyuzhang1991 LV10
2016年4月6日
AXIN LV36
2014年2月25日