字典(映射)
java.util.Map
- HashMap
- TreeMap
- Map<v,k> - v代表键的类型,k代表值的类型
- 取元素用get取值,里面传键,得到键所对应的值
public class Test01 {
public static void main(String[] args) {
//Map<Integer, String> map = new HashMap<>();
Map<Integer, String> 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<T extends Comparable<T>> 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<T> void bubbleSort(T[] array,Comparator<T> 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<Student>() {//创造匿名内部类,就地实现
@Override
public int compare(Student o1, Student o2) {
return o1.getAge() - o2.getAge();
}
});
System.out.println(Arrays.toString(students));
}