java 泛型map_Java--Map及泛型

字典(映射)

java.util.Map

HashMap

TreeMap

Map - v代表键的类型,k代表值的类型

取元素用get取值,里面传键,得到键所对应的值

public class Test01 {

public static void main(String[] args) {

//Map map = new HashMap<>();

Map map = new TreeMap<>();

map.put(1, "apple");//添加

map.put(2, "grape");

map.put(100, "shit");

map.put(1, "banana");

//执行完了后,apple被改成了banana

System.out.println(map.size());

//map.remove(100);//删除

//map.clear();//清空

for (Integer key : map.keySet()) {

System.out.println(key + " ---> " + map.get(key));

}

}

}

泛型(generic)

让类型不再是程序中的硬代码(hard code)

T代表引用类型,但是不能是基本数据类型

//T类型实现了comparable接口

//此处的extends不是继承而是泛型限定,限定T类型必须是comparable接口的子类型

public static> void bubbleSort(T[] array){

boolean swapped = true;

for (int i = 1; swapped && i < array.length; i++) {

swapped = false;

for (int j = 0; j < array.length - i; j++) {

if (array[j].compareTo(array[j + 1]) > 0) {

T temp = array[j];

array[j] = array[j + 1];

array[j + 1] = temp;

swapped = true;

}

}

}

}

//T类型没有实现接口

public static void bubbleSort(T[] array,Comparator comp){

boolean swapped = true;

for (int i = 1; swapped && i < array.length; i++) {

swapped = false;

for (int j = 0; j < array.length - i; j++) {

if (comp.compare(array[j],array[j + 1]) > 0) {

T temp = array[j];

array[j] = array[j + 1];

array[j + 1] = temp;

swapped = true;

}

}

}

}

测试代码

public static void main(String[] args) {

Student[] students = {new Student("wangdachui", 18),

new Student("limochou", 25),

new Student("zhangsanfeng", 100)};

//String[] x = {"killer","grape","zoo","blueberry","apple"};

//Integer[] x = {12,4,45,36,50,67};

//Double[] y = {2.0,3.2,1.5,10.0};

//bubbleSort(students);

bubbleSort(students,(o1,o2)-> {//lambda表达式

return o1.getName().compareTo(o2.getName());

});

bubbleSort(students,new Comparator() {//创造匿名内部类,就地实现

@Override

public int compare(Student o1, Student o2) {

return o1.getAge() - o2.getAge();

}

});

System.out.println(Arrays.toString(students));

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值