import java.util.*;
class TestHashMap
{
public static void main( String[] args){
//Map<String, String> map = new HashMap<String, String>();
Map<String, String> map = new TreeMap<String, String>();
map.put("one", "一");
map.put("two", "二");
map.put("three", "三");
map.put("four", "四");
map.put(new String("five"), "五");
map.put(new String("five"), "五二");
map.put("six", "四");
System.out.println( map.get("three") );
for( String key : map.keySet() )
System.out.println( key +":" + map.get(key) );
for( String value : map.values() )
System.out.println( value );
for( Map.Entry<String,String> entry : map.entrySet() )
System.out.println( entry.getKey() +":" + entry.getValue() );
Iterator it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String,String> entry = (Map.Entry<String,String>)it.next();
System.out.println( entry.getKey() +":" + entry.getValue() );
}
}
}
9.排序和查找
*Arrays类
用于对数组进行排序和搜索的类
Arrays类提供了sort()和binarySearch()
*Collection类
import java.util.*;
class TestCollectionsSort
{
public static void main(String[] args)
{
List<Person> school = new ArrayList<Person>();
school.add( new Person("Li",23));
school.add( new Person("Wang",28));
school.add( new Person("Zhang",21));
school.add( new Person("Tang",19));
school.add( new Person("Chen",22));
school.add( new Person("Zhao",22));
System.out.println( school );
Collections.sort( school, new PersonComparator() );
System.out.println( school );
int index = Collections.binarySearch(
school, new Person("Li",23), new PersonComparator() );
if( index >=0 )
System.out.println( "Found:" + school.get( index ));
else
System.out.println( "Not Found!" );
}
}
class Person
{
String name;
int age;
public Person( String name, int age){
this.name=name;
this.age=age;
}
public String toString(){
return name+":"+age;
}
}
class PersonComparator implements Comparator
{
public int compare( Object obj1, Object obj2 ){
Person p1 = (Person)obj1;
Person p2 = (Person)obj2;
if( p1.age > p2.age ) return 1;
else if(p1.age<p2.age) return -1;
return p1.name.compareTo( p2.name );
}
}
明天学习内容:泛型,常用算法