首页 > 编程学习 > map常用·方法

map常用·方法

发布时间:2022/2/7 9:36:13

Map集合 键值对存在

Map在通过键取值时,取键,用set集合(无序的,不可重复的)

取值,用collection集合

  1. map通过键来取值

 

  1. treemap集合:

Student:

public class student implements Comparable<student>{

private String name;

private int age;

public student() {

}

public student(String name, int age) {

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;

}

@Override

public String toString() {

return "student [name=" + name + ", age=" + age + "]";

}

@Override

public int compareTo(student o) {

// TODO Auto-generated method stub

int a=this.age-o.age;

//姓名如果相等 ,重新调用这个方法,来比较名字

int a1=this.name.compareTo(name);

return a==0? a1:a;

}

}

Demo1:

public class Demo1 {

public static void main(String[] args) {

//对name age 的对象进行夫赋值

student stu1=new student("张三",11);

student stu2=new student("李四",50);

student stu3=new student("赵五",34);

student stu4=new student("王六",23);

TreeMap<student, String> map = new TreeMap<student, String>();

map.put(stu1, "唱歌");

map.put(stu2, "跳舞");

map.put(stu3, "绘画");

map.put(stu4, "跳高");

System.out.println(map);//注意,会报错

//对象需要重写compareoTo方法

//{student [name=张三, age=11]=唱歌,

// student [name=王六, age=23]=跳高,

// student [name=赵五, age=34]=绘画,

// student [name=李四, age=50]=跳舞}

}

}

Copyright © 2010-2022 ngui.cc 版权所有 |关于我们| 联系方式| 豫B2-20100000