容器--Map(键值对)
package Day12_22_00;
import java.util.HashMap;
import java.util.Map;
/*
* 映射(字典-根据相应的键可查找对应的值)
* java.util.Map
* -HashMap
* -TreeMap
*/
public class Test001
{
public static void main(String[] args)
{
Map map=new HashMap<>();
map.put(1, "apple");
map.put(2, "grape");
map.put(100, "shit");
//加入了新的相同键,会把之前的值覆盖了(apple被banana覆盖了)
map.put(1, "banana");
System.out.println(map.size());
//根据键来删除元素
map.remove(100);
for (Integer key : map.keySet())
{
System.out.println(key+"-->"+map.get(key));
}
}
}
最具逼格的冒泡排序
lambda表达式,匿名内部类的使用
泛型的使用
package Day12_22_00;
import java.util.Arrays;
import java.util.Comparator;
//最具逼格的冒泡排序
public class Test002
{
/*
* 泛型(generic)-让类型不再是程序中的硬代码(hard code)
*
* >--T代表的是引用类型,不是基本类型 此处的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;
}
}
}
}
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)
{
Double[] aa =
{ 1.0, 34., 5., 7., 3., 98., 54. };
Student[] stu =
{
new Student("汪汪汪", 17),
new Student("喵喵喵", 45),
new Student("王焕琪", 23)
};
bubbleSort(stu);
System.out.println(Arrays.toString(stu));
// bubbleSort(stu,new Comparator()
// {
//
// @Override
// public int compare(Student o1, Student o2)
// {
// return o1.getAge()-o2.getAge();
// }
// });
//lambda表达式
bubbleSort(stu, (o1,o2)->{
return o1.getAge()-o2.getAge();
});
System.out.println(Arrays.toString(stu));
bubbleSort(aa);
System.out.println(Arrays.toString(aa));
}
}
class Student implements Comparable
{
private int age;
private String name;
public Student(String name, int age)
{
this.age = age;
this.name = name;
}
@Override
public String toString()
{
return name + ":" + age;
}
@Override
public int compareTo(Student o)
{
return -this.name.compareTo(o.name);
}
public int getAge()
{
return age;
}
}