16
2018
12

JAVA学习-java集合之TreeMap

java集合之TreeMap

TreeMap类通过使用红黑树实现Map接口,键不能为null

TreeMap提供按排序顺序存储键/值对的有效手段,同时允许快速检索

不像散列映射,树映射保证它的元素按关键字升序排序

TreeMap构造方法:

TreeMap()

TreeMap(Comparator comp)

TreeMap(Map m)

TreeMap(SortedMap sm)

TreeMap实现SortedMap并且扩展AbstractMap,它本身并没有定义其他方法


demo:

package pkg1.TreeMap;
import java.util.Comparator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
public class TreeMapDemo {
public static void main(String[] args) {
test1();
test2();
}
public static void test1() {
TreeMap<String, String> map = new TreeMap<String, String>();
map.put("zs", "张三");
map.put("ls", "李四");
map.put("ww", "王五");
System.out.println(map);// 输出,按键排序
// 使用方法大部分与HashMap一致
Set<Entry<String, String>> entrySet = map.entrySet();
for (Entry<String, String> kv : entrySet) {
System.out.print(kv.getKey() + " " + kv.getValue() + "\n");
}
System.out.println("-----------------------");
}
public static void test2() {
TreeMap<Person, String> map = new TreeMap<Person, String>(
/*
// 参数实现Comparator接口与对象中实现Comparable接口效果一样
new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
if (o1.getName().compareTo(o2.getName()) != 0) {
return o1.getName().compareTo(o2.getName());
}
int temp = o1.getAge() - o2.getAge();
if (temp > 0)
return 1;
else if (temp < 0)
return -1;
else
return 0;
}
}
*/
);
map.put(new Person("zs", 20), "张三");
map.put(new Person("ls", 10), "李四");
map.put(new Person("ww", 15), "王五");
map.put(new Person("zs", 3), "小张三");
System.out.println(map);
}
}
// 作为TreeMap的Key时,必须实现Comparable<T>接口或在定义TreeMap对象时传入比较方法的实现
class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return name + " " + age;
}
@Override
public int compareTo(Person o) {// 自定义排序 ,按年龄从小到大
if (o == null)
return 1;
// 先按姓名比较,如果姓名相同,再按年龄比较
// if(name.compareTo(o.name) != 0) return name.compareTo(o.name);
int temp = age - o.getAge();
if (temp > 0)
return 1;
else if (temp < 0)
return -1;
else
return 0;
}
}


效果:



版权声明:
作者:真爱无限 出处:http://www.pukuimin.top 本文为博主原创文章版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接.
« 上一篇下一篇 »

相关文章:

评论列表:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。