集合本质是容器。容器可以装很多类型的数据。Collection是集合的根类。容器的特性自动扩容。
存储器 | 存储数据长度 | 存储数据类型单一性 | 存储数据类型的要求 |
---|---|---|---|
数组 | 固定 | 只能存储同类型数据 | 引用类型、对象类型、基本类型、包装类型 |
集合 | 可变 | 可以存储不同类型数据 | 引用类型、对象类型、包装类型 |
package com.xzy.JavaCollectionsFramWork.Code.java.util.Collection;
public class Student {
private String name;
private Integer age;
public Student() {
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.Collection;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* @Class CollectionP
* @Description
* @Author xuzhiyong
* @DateTime 2020/6/3 19:52
* @Version 1.0
*/
public class CollectionP {
//日志记录
private static Logger logger = LoggerFactory.getLogger(CollectionP.class);
public static void main(String[] args) {
}
public static void commonMethod5() {
Collection c=new ArrayList();
Student stu1 = new Student("zz", 31);
Student stu2 = new Student("tt", 22);
Student stu3 = new Student("yy", 18);
c.add(stu1);
c.add(stu2);
c.add(stu3);
System.out.println(c);
//数组遍历
Object[] ob= c.toArray();
for (int i = 0; i < ob.length; i++) {
Student st = (Student) ob[i];
System.out.println(st.getName()+"::"+st.getAge());
}
//迭代器遍历
System.out.println("---------[42]-------");
Iterator it = c.iterator();
while (it.hasNext()) {
Student next = (Student) it.next();
System.out.println(next.getName() + ":::" + next.getAge());
}
//for循环遍历
System.out.println("---------[52]-------");
for(Iterator iterator=c.iterator();iterator.hasNext();){
Object next = iterator.next();
Student stu = (Student) next;
System.out.println(stu.getName() + ":::" + stu.getAge());
}
}
public static void iterator4() {
Collection c=new ArrayList();
c.add("Java");
c.add("Python");
c.add("C++");
Object[] ob = c.toArray();
for (Object o : ob) {
System.out.println(o);
}
System.out.println("---------[31]-------");
for (int i = 0; i < ob.length; i++) {
System.out.println(ob[i]);
}
System.out.println("---[36]---");
//通过集合得到实现了该接口的迭代器对象
Iterator it = c.iterator();
while (it.hasNext()) {
Object next = it.next();
System.out.println(next);
}
}
public static void commonMethod3() {
Collection c1=new ArrayList();
Collection c2=new ArrayList();
c1.add("Java");
c1.add("C++");
c1.add("Python");
c3.add("hello");
c3.add("world");
c3.add("Java");
System.out.println(c1.contains(c2));
System.out.println(c1);
System.out.println(c2);
System.out.println("--------------------[37]--------------------");
System.out.println(c1.retainAll(c2));
System.out.println(c1);
System.out.println(c2);
}
public static void commonMethod2() {
Collection c1=new ArrayList();
Collection c2=new ArrayList();
c1.add("good");
c1.add("hello");
c3.add("hello");
c1.addAll(c2);
c1.retainAll(c2);
// c1.removeAll(c2);
System.out.println(c1);
System.out.println(c2);
}
public static void commonMethod1() {
Collection c = new ArrayList();
c.add("hello");
c.add("hello");
c.add("hello");
c.add("Java");
c.add("Java");
c.add("Java");
System.out.println(c.remove("java"));
System.out.println(c.remove("Java"));
System.out.println(c);
System.out.println("----");
for (Object o : c) {
if (o.equals("hello")) {
System.out.println(o);
}
}
System.out.println("--------------------[]--------------------");
System.out.println(c.contains("hello"));
System.out.println(c);
System.out.println(c.isEmpty());
System.out.println(c.size());
c.clear();
}
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.List;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* @Class ListP
* @Description List特有方法练习
* - void add(int index,Object element)注定位置添加元素
* - Object get(int index)获取指定位置的元素
* - Object remove(int index)根据索引删除元素,返回被删除的元素
* - Object set(int index,Object element)根据索引修改元素,返回被修改的元素
* - List subList(int fromIndex, int toIndex)返回列表中指定的 fromIndex(包括 )和 toIndex(不包括)之间的部分视图。
* - int indexOf(Object o)返回此列表中第一次出现的指定元素的索引;如果此列表不包含该元素,则返回 -1。
* - int lastIndexOf(Object o)返回此列表中最后出现的指定元素的索引;如果列表不包含此元素,则返回 -1。
* @Author xuzhiyong
* @DateTime 2020/6/4 9:42
* @Version 1.0
*/
public class ListP {
//日志记录
private static Logger logger = LoggerFactory.getLogger(ListP.class);
public static void main(String[] args) {
}
public static void commonMethod1() {
List list = new ArrayList();
list.add("Java");
list.add("Python");
list.add("Python");
list.add(2,"Go");
// list.add(4,"Go");//IndexOutOfBoundsException
for (Object o : list) {
System.out.println(o);
}
System.out.println("---------[40]-------");
Iterator it = list.iterator();
while (it.hasNext()) {
String str = (String) it.next();
System.out.println(str);
}
System.out.println("---------[42]-------");
for (int i = 0; i < list.size(); i++) {
String str = (String) list.get(i);
System.out.println(str);
}
System.out.println("---------[47]-------");
System.out.println(list.remove("Python3"));//Collection中的方法
System.out.println("---------[51]-------");
for (Object o : list) {
System.out.println(o);
}
System.out.println("---------[59]-------");
System.out.println(list.remove(2));//List中的方法
System.out.println("---------[56]-------");
for (Object o : list) {
System.out.println(o);
}
System.out.println("---------(set)[66]-------");
System.out.println(list.set(0, "String"));
System.out.println("---------()[68]-------");
for (Object o : list) {
System.out.println(o);
}
System.out.println("---------(subList)[75]-------");
System.out.println(list.subList(0, 2));
System.out.println("---------()[77]-------");
System.out.println(list.indexOf("String"));
System.out.println("---------()[79]-------");
System.out.println(list.lastIndexOf("Python"));
}
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.ListIterator;
public class Student {
private String name;
private Integer age;
public Student() {
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.ListIterator;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import java.util.*;
/**
* @Class ListIteratorP
* @Description listIterator特有方法练习
* - void add(E e)将指定的元素插入列表(可选操作)。
* - boolean hasNext()以正向遍历列表时,如果列表迭代器有多个元素,则返回 true(换句话说,如果 next 返回一个元素而不是抛出异常,则返回 true)。
* - boolean hasPrevious()如果以逆向遍历列表,列表迭代器有多个元素,则返回 true。
* - E next()返回列表中的下一个元素。
* - int nextIndex()返回对 next 的后续调用所返回元素的索引。
* - E previous()返回列表中的前一个元素。
* - int previousIndex()返回对 previous 的后续调用所返回元素的索引。
* - void remove()从列表中移除由 next 或 previous 返回的最后一个元素(可选操作)。
* - void set(E e)用指定元素替换 next 或 previous 返回的最后一个元素(可选操作)。
* @Author xuzhiyong
* @DateTime 2020/6/4 10:40
* @Version 1.0
*/
public class ListIteratorP {
//日志记录
private static Logger logger = LoggerFactory.getLogger(ListIteratorP.class);
public static void main(String[] args) {
}
public static void commonMethod2() {
List l=new ArrayList();
l.add(new Student("Tom",20));
l.add(new Student("Robot",19));
l.add(new Student("Bob",25));
l.add(new Student("Sily",18));
System.out.println("---------()[1]-------");
ListIterator lis = l.listIterator();
while (lis.hasNext()) {
System.out.println(lis.next());
}
System.out.println("---------()[2]-------");
for (int i = 0; i < l.size(); i++) {
System.out.println(l.get(i));
}
System.out.println("---------()[3]-------");
Iterator it = l.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
System.out.println("---------()[4]-------");
for (Object o : l) {
System.out.println(o);
}
}
public static void commonMethod1() {
List list = new ArrayList();
list.add("Java");
list.add("Python");
list.add("C++");
list.add("Go");
System.out.println("---------(顺序遍历)[32]-------");
ListIterator li = list.listIterator();
while (li.hasNext()) {
System.out.println(li.next());
}
System.out.println("---------(逆序遍历)[35]-------");
while (li.hasPrevious()) {
System.out.println(li.previous());
}
System.out.println("---------(指定位置开始遍历)[42]-------");
ListIterator li2 = list.listIterator(2);
while (li3.hasNext()) {
System.out.println(li3.next());
}
System.out.println("---------(指定位置逆遍历)[47]-------");
System.out.println(li3.hasNext());//这货底层还是临时变量
System.out.println("---------(list元素)[50]-------");
for (Object o : list) {
System.out.println(o);
}
System.out.println("---------()[55]-------");
System.out.println(li.next());
System.out.println(li.next());
System.out.println("---------()[58]-------");
System.out.println(li.previous());
System.out.println(li.previous());
list.clear();
System.out.println(list.size());
System.out.println("---------()[71]-------");
list.add("Java");
list.add("C++");
list.add("Python");
list.add("R");
for (Object o : list) {
System.out.println(o);
}
//普通添加元素
for (int i = 0; i < list.size(); i++) {
Object o = list.get(i);
if (o.equals("C++")) {
list.add("Go");
break;
}
}
System.out.println(list);
//迭代器添加元素,在本次迭代元素之后添加元素
ListIterator lis = list.listIterator();
while (lis.hasNext()) {
Object next = lis.next();
if (next.equals("R")) {
lis.add("Ruby");
break;
}
}
System.out.println(list);
}
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.ArrayList;
import java.util.Objects;
public class Teacher extends Person {
private Integer salary;
@Override
public String getName() {
return super.getName();
}
@Override
public void setName(String name) {
super.setName(name);
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Teacher teacher = (Teacher) o;
return Objects.equals(salary, teacher.salary);
}
@Override
public int hashCode() {
return Objects.hash(salary);
}
public Integer getSalary() {
return salary;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
public Teacher() {
}
public Teacher(String name,Integer salary) {
this.salary = salary;
super.setName(name);
}
public void showTeacher(){
System.out.println("Teacher"+":"+super.getName()+":"+salary);
}
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.ArrayList;
import java.util.Objects;
public class Student extends Person{
private Integer grade;
public Student(Integer grade) {
this.grade = grade;
}
public Integer getGrade() {
return grade;
}
public void setGrade(Integer grade) {
this.grade = grade;
}
@Override
public String getName() {
return super.getName();
}
@Override
public String toString() {
return "Student{" +
"grade=" + grade +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return Objects.equals(grade, student.grade);
}
@Override
public int hashCode() {
return Objects.hash(grade);
}
@Override
public void setName(String name) {
super.setName(name);
}
public Student(String name, Integer grade) {
super(name);
this.grade = grade;
}
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.ArrayList;
public class Person {
private String name;
public String getName() {
return name;
}
public Person() {
}
public Person(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public void showPerson(){
System.out.println("Person"+":"+name);
}
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.ArrayList;
public class MyGenericInterfaceImpl implements MyGenericInterface {
@Override
public void show(K e) {
System.out.println(e);
}
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.ArrayList;
public interface MyGenericInterface {
public abstract void show(K e);
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.ArrayList;
import java.util.Objects;
/**
* @Class MyGenericClassAndMethod
* @Description 自定义泛型类、泛型方法,默认Object类型,创建对象可以不加泛型,也可以传入泛型参数
* @Author xuzhiyong
* @DateTime 2020/6/5 11:04
* @Version 1.0
*/
public class MyGenericClassAndMethod {
private E name;
private T age;
//方法的参数泛型是成对出现的,void前和参数列表对应
public void add(K k, V v) {
System.out.println(k + ":::" + v);
}
public void show() {
System.out.println("good");
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyGenericClassAndMethod, ?> that = (MyGenericClassAndMethod, ?>) o;
return Objects.equals(name, that.name) &&
Objects.equals(age, that.age);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return "MyGenericClassAndMethod{" +
"name=" + name +
", age=" + age +
'}';
}
public E getName() {
return name;
}
public void setName(E name) {
this.name = name;
}
public T getAge() {
return age;
}
public void setAge(T age) {
this.age = age;
}
public MyGenericClassAndMethod(E name, T age) {
this.name = name;
this.age = age;
}
public MyGenericClassAndMethod() {
}
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.ArrayList;
import java.util.*;
/**
* @Class ArrayListP
* @Description 迭代器遍历、集合泛型
* @Author xuzhiyong
* @DateTime 2020/6/4 15:33
* @Version 1.0
*/
public class ArrayListP {
public static void main(String[] args) {
}
public static void method15() {
//创建集合
ArrayList integers = new ArrayList<>();
//创建数组
Integer[] integers1 = new Integer[integers.size()];
//数组转集合
List integers2 = Arrays.asList(integers1);
//集合转数组
Integer[] integers3 = integers.toArray(integers1);
//数组排序
Arrays.sort(integers3);
}
public static Integer judge(Integer...args){
Integer number=args[0];
Integer max=number;
for (int i = 1; i < args.length; i++) {
if (args[i]>number) {
max=args[i];
}
}
return max;
}
public static void method14() {
ArrayList numbers1 = new ArrayList<>();
//低版本
for (int i = 0; i < 100; i++) {
if (numbers1.size() >9) {
continue;
} else {
int num = (int) (Math.random() * 20 + 1);
if (!numbers1.contains(num)) {
numbers1.add(num);
}
}
}
for (Integer number : numbers1) {
System.out.println(numbers1.size()+":::"+number);
}
//最优版本
ArrayList numbers2 = new ArrayList<>();
int count=0;
while (count<10){
int num = (int) (Math.random() * 20 + 1);
if (!numbers1.contains(num)) {
numbers1.add(num);
}
}
for (Integer integer : numbers2) {
System.out.println(numbers3.size()+":::"+integer);
}
}
public static void method11() {
ArrayList> course = new ArrayList<>();
ArrayList java1 = new ArrayList<>();
ArrayList java2 = new ArrayList<>();
com.xzy.javaapi.java.util.arrays.Student s1 = new com.xzy.javaapi.java.util.arrays.Student("xzy", 20);
com.xzy.javaapi.java.util.arrays.Student s2 = new com.xzy.javaapi.java.util.arrays.Student("Bill", 18);
com.xzy.javaapi.java.util.arrays.Student s3 = new com.xzy.javaapi.java.util.arrays.Student("Tom", 22);
java1.add(s1);
java1.add(new com.xzy.javaapi.java.util.arrays.Student("Sily", 23));
java1.add(new com.xzy.javaapi.java.util.arrays.Student("King", 25));
java3.add(s2);
java3.add(s3);
course.add(java1);
course.add(java2);
//第一种增强for
int x = 1;
for (ArrayList students : course) {
System.out.println(x);
for (com.xzy.javaapi.java.util.arrays.Student student : students) {
System.out.println(student.getName() + "::" + student.getAge());
}
x++;
}
x--;
x--;
System.out.println("---------()[" + getLineNumber() + "]-------");
//第二种普通迭代器遍历
Iterator> iterator = course.iterator();
while (iterator.hasNext()) {
System.out.println(x);
ArrayList next = iterator.next();
Iterator iterator1 = next.iterator();
while (iterator1.hasNext()) {
com.xzy.javaapi.java.util.arrays.Student next1 = iterator1.next();
System.out.println(next1.getName() + "---" + next1.getAge());
}
x++;
}
x--;
x--;
System.out.println("---------()[" + getLineNumber() + "]-------");
//第三种集合迭代器遍历,正向展开
ListIterator> arr = course.listIterator();
while (arr.hasNext()) {
System.out.println(x);
ArrayList next = arr.next();
ListIterator st = next.listIterator();
while (st.hasNext()) {
com.xzy.javaapi.java.util.arrays.Student previous = st.next();
System.out.println(previous.getName() + previous.getAge());
}
x++;
}
x--;
x--;
System.out.println("---------(正向遍历完成)[" + getLineNumber() + "]-------");
while (arr.hasPrevious()) {
System.out.println(x);
ArrayList previous = arr.previous();
//不使用for循环,使用纯粹的List迭代器能否实现多维数组的循环遍历逆向打印。
for (com.xzy.javaapi.java.util.arrays.Student student : previous) {
System.out.println(student.getName() + student.getAge());
}
x++;
}
x--;
x--;
System.out.println("---------(逆向遍历)[" + getLineNumber() + "]-------");
//第四种,数组遍历
for (int i = 0; i < course.size(); i++) {
System.out.println(x);
ArrayList st = course.get(i);
for (int j = 0; j < st.size(); j++) {
com.xzy.javaapi.java.util.arrays.Student student = st.get(j);
System.out.println(student.getName() + student.getAge());
}
x++;
}
x--;
x--;
System.out.println("---------(数组遍历)[" + getLineNumber() + "]-------");
}
/**
* @Method {@link }{@link ArrayListP#method12()}T(n)=O(n)
* @Description 增强for循环,被遍历的集合或数组不能为空,即null,底层是迭代器
* @Version 1.0
*/
public static void method13() {
String[] arr = {"Java", "C++", "R"};
for (String s : arr) {
System.out.println(s);
}
System.out.println("---------()[" + getLineNumber() + "]-------");
ArrayList strs = new ArrayList<>();
strs.add("Java");
strs.add("C++");
strs.add("R");
strs.add(null);
for (String str : strs) {
System.out.println(str);
}
}
/**
* @Method {@link Void}{@link ArrayListP#method11()}T(n)=O()
* @Description 向上界定通配符 super E>,迭代器不能有null,否则会报空指针异常
* @Version 1.0
*/
public static void method12() {
//测试区
ArrayList> objects = new ArrayList<>();//可以任意类型,
ArrayList super Person> objects1 = new ArrayList<>();//可以添加Student、Person、null,null不能使用迭代器遍历,否则NullPointException
ArrayList super Teacher> objects2 = new ArrayList<>();//可以添加Student、null,null不能使用迭代器遍历,否则NullPointException
objects1.add(null);
objects1.add(new Teacher());
objects1.add(new Person());
objects3.add(new Teacher());
// objects3.add(new Person());//错误,感觉和extends一样,区别是super可以直接限定为最大的类型
//正式测试区
System.out.println("---------()[" + getLineNumber() + "]-------");
ArrayList teachers = new ArrayList<>();
ArrayList people = new ArrayList<>();
ArrayList he = new ArrayList<>();
teachers.add(new Teacher("Tom", 20000));
teachers.add(new Teacher("Bob", 15000));
teachers.add(new Teacher("Bill", 30000));
people.add(new Teacher());
people.add(new Person());
method10(teachers);
System.out.println("---------()[" + getLineNumber() + "]-------");
method7(teachers);
method7(he);
method9(teachers);
}
public static void method10(List super Teacher> list) {
Iterator super Teacher> it = list.iterator();
while (it.hasNext()) {
Object next = it.next();
Teacher next1 = (Teacher) next;
System.out.println(next1.getName() + ":" + next1.getSalary());
}
}
public static void method9(List extends Teacher> list) {
Iterator extends Teacher> it = list.iterator();
while (it.hasNext()) {
Teacher next = it.next();
System.out.println(next.getName() + ":" + next.getSalary());
}
}
/**
* @Method {@link Void}{@link ArrayListP#method8()}
* @Description 向下界定通配符 super T>
* @T(n)
* @Version 1.0
*/
public static void method8() {
//创建测试
Person person = new Person();
Teacher teacher = new Teacher();
Person person1 = new Teacher();//对象多态
Person[] people1 = new Teacher[20];//数组支持多态
ArrayList people = new ArrayList<>();
ArrayList teachers = new ArrayList<>();
// ArrayList p=new ArrayList();集合泛型不支持自动多态
//使用通配符限定父类
//第一种
ArrayList extends Person> p1 = new ArrayList();//多态1
//第二种
ArrayList> p2 = new ArrayList();//多态2
p1 = new ArrayList();//赋值测试
p1 = new ArrayList();//赋值测试
//创建集合
ArrayList teachers3 = new ArrayList<>();
ArrayList extends Person> arrayList = new ArrayList<>();
arrayList = teachers3;
//泛型参数需要是方法规定的向下界定泛型的本身或者子类
method7(teachers);
method7(people);
method7(arrayList);
method7(teachers3);
//打印测试
ArrayList teaTest = new ArrayList<>();
teaTest.add(new Teacher("Tom", 10000));
teaTest.add(new Teacher("Bob", 20000));
teaTest.add(new Teacher("Bill", 15000));
method7(teaTest);
}
public static void method7(List extends Person> list) {
Iterator extends Person> it = list.iterator();
while (it.hasNext()) {
Person next = it.next();
Teacher next1 = (Teacher) next;
System.out.println(next1.getName() + ":" + next1.getSalary());
}
}
public static void method6() {
MyGenericInterface str = new MyGenericInterfaceImpl<>();
str.show("gggg");
}
public static void method5() {
MyGenericClassAndMethod str = new MyGenericClassAndMethod<>();
str.add("20", 19);
System.out.println("---------()[" + getLineNumber() + "]-------");
str.show();
}
public static void method4() {
ArrayList st1 = new ArrayList<>();
ArrayList st2 = new ArrayList<>();
st1.add(new Student("Tom", 25));
st1.add(new Student("Sily", 24));
st1.add(new Student("Sily", 24));
st1.add(new Student("King", 18));
st1.add(new Student("Bob", 19));
st1.add(new Student("Bob", 19));
st1.add(new Student("Bob", 19));
st1.add(new Student("Ben", 26));
st1.add(new Student("Bob", 19));
st1.add(new Student("Ben", 26));
st1.add(new Student("Bill", 30));
ListIterator lis = st1.listIterator();
while (lis.hasNext()) {
Student st = lis.next();
//contains底层依赖的是equals方法,没有重写的equals方法比较的首先会比较地址值,需要重写Student对象中的equals方法
if (!st3.contains(st)) {//看清楚condition是什么,每次都菜的一逼
st3.add(st);
}
}
System.out.println("---------()[" + getLineNumber() + "]-------");
System.out.println(st2);
System.out.println("---------()[" + getLineNumber() + "]-------");
//只有正遍历才能调用逆向遍历
ListIterator lis2 = st3.listIterator();
while (lis3.hasNext()) {
lis3.next();
}
System.out.println("---------()[" + getLineNumber() + "]-------");
while (lis3.hasPrevious()) {
System.out.println(lis3.previous());
}
}
public static void method3() {
ArrayList st = new ArrayList<>();
Student s1 = new Student("xzy", 20);
Student s2 = new Student("Robot", 18);
Student s3 = new Student("Tom", 25);
st.add(s1);
st.add(s2);
st.add(s3);
System.out.println("---------()[" + getLineNumber() + "]-------");
Iterator it = st.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
System.out.println("---------()[" + getLineNumber() + "]-------");
//使用逆向遍历,需要先正向遍历,才能再逆向遍历
ListIterator lit = st.listIterator();
while (lit.hasNext()) {
System.out.println(lit.next());
}
System.out.println("---------()[" + getLineNumber() + "]-------");
while (lit.hasPrevious()) {
System.out.println(lit.previous());
}
}
public static void method2() {
//泛型参数化JDK1.5之后引入
//泛型推断JDK1.7新特性
ArrayList strs = new ArrayList<>();
strs.add("Java");
strs.add("Go");
strs.add("R");
Iterator it = strs.iterator();
while (it.hasNext()) {
String str = it.next();
System.out.println(str);
}
}
public static void method1() {
ArrayList arr = new ArrayList();
arr.add("Java");
arr.add("R");
arr.add("Go");
arr.add("Python");
arr.add("C++");
Iterator it = arr.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
System.out.println("---------()[" + getLineNumber() + "]-------");
arr.add(new Student("xzy", 20));
arr.add(new Student("Tom", 18));
arr.add(new Student("Bob", 19));
arr.add(new Student("King", 25));
Iterator it2 = arr.iterator();
while (it3.hasNext()) {
System.out.println(it3.next());
}
}
public static int getLineNumber() {
int level = 1;
StackTraceElement[] stacks = new Throwable().getStackTrace();
int lineNumber = stacks[level].getLineNumber();
return lineNumber;
}
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.Vector;
public class Student {
private String name;
private Integer age;
public Student() {
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.Vector;
import java.util.Enumeration;
import java.util.Vector;
/**
* @Class VectorP
* @Description Vector特有方法练习
* - void addElement(Object obj)添加指定对象到集合中
* - Object elementAt(int index)返回指定索引处的元素
* - Enumeration elements()获得迭代器
* - boolean hasMoreElements()判断迭代器指向的下一个元素是否存在
* - Object nextElement()返回迭代器指向的下一个元素
* @Author xuzhiyong
* @DateTime 2020/6/4 17:04
* @Version 1.0
*/
public class VectorP {
public static void main(String[] args) {
Vector ve = new Vector();
ve.addElement(new Student("Tom",20));
ve.addElement(new Student("King",25));
ve.addElement(new Student("Sally",19));
System.out.println(ve.elementAt(0));
System.out.println("---------()[29]-------");
Enumeration el = ve.elements();
while (el.hasMoreElements()) {
System.out.println(el.nextElement());
}
}
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.LinkedList;
import java.util.LinkedList;
/**
* @Class MyStack
* @Description 使用链表集合模拟栈先进后出
* @Author xuzhiyong
* @DateTime 2020/6/4 21:23
* @Version 1.0
*/
public class MyStack {
LinkedList li=new LinkedList();
public void add(Object o){
li.addFirst(o);
}
@Override
public String toString() {
return "MyStack{" +
"li=" + li +
'}';
}
public Object pop(){
return li.removeFirst();
}
public Boolean isEmpty(){
return li.isEmpty();
}
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.LinkedList;
import java.util.LinkedList;
/**
* @Class MyQueue
* @Description 使用链表集合模拟队列先进先出
* @Author xuzhiyong
* @DateTime 2020/6/4 21:24
* @Version 1.0
*/
public class MyQueue {
LinkedList li=new LinkedList();
public void add(Object o){
li.addFirst(o);
}
public Object pop(){
return li.removeLast();
}
public Boolean isEmpty(){
return li.isEmpty();
}
@Override
public String toString() {
return "MyQueue{" +
"li=" + li +
'}';
}
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.LinkedList;
import java.util.ArrayList;
import java.util.LinkedList;
/**
* @Class LinkedListP
* @Description LinkedList特有方法
* - void addFirst(Person e)在索引为0的位置添加对象
* - void addLast(Person e)在集合末尾欠佳元素
* - Person getFirst()获得集合首个元素
* - Person getLast()获得集合末尾元素
* - Person removeFirst()删除集合首个元素
* - Person removeLast()删除集合末尾元素
* @Author xuzhiyong
* @DateTime 2020/6/4 17:34
* @Version 1.0
*/
public class LinkedListP {
public static void main(String[] args) {
removeRepeatingElements5();
}
public static void removeRepeatingElements5() {
//去除arr1中的重复元素,2个集合实现,O(n)
ArrayList arr1 = new ArrayList();
ArrayList arr2 = new ArrayList();
arr1.add("Java");
arr1.add("R");
arr1.add("R");
arr1.add("Go");
arr1.add("Go");
arr1.add("Python");
arr1.add("Python");
arr1.add("C++");
arr1.add("C++");
for (Object o : arr1) {
if (!arr3.contains(o)) {
arr3.add(o);
}
}
System.out.println(arr2);
//去除arr1中的重复元素,1个集合实现,O(n^2),写完了给自己打个分好复杂!哈哈
System.out.println("---------()[47]-------");
arr1.clear();
arr3.clear();
arr1.add("Java");
arr1.add("Java");
arr1.add("R");
arr1.add("Java");
arr1.add("Java");
arr1.add("R");
arr1.add("Go");
arr1.add("Go");
arr1.add("Python");
arr1.add("Python");
arr1.add("C++");
arr1.add("C++");
ArrayList arr = new ArrayList();
for (int i = 0; i < arr1.size()-1; i++) {
for (int j = i+1; j < arr1.size(); j++) {
if (arr1.get(i).equals(arr1.get(j))) {
arr.add(j);
}
}
}
for (Object o : arr) {
arr1.set((Integer) o,"##");
}
for (int i = 0; i < arr.size(); i++) {
arr1.remove("##");
}
System.out.println(arr1);
//去除arr1中的重复元素,1个集合实现,简单算法
System.out.println("---------()[85]-------");
arr1.clear();
arr3.clear();
arr.clear();
arr1.add("Java");
arr1.add("Java");
arr1.add("R");
arr1.add("Java");
arr1.add("Java");
arr1.add("R");
arr1.add("Go");
arr1.add("Go");
arr1.add("Python");
arr1.add("Python");
arr1.add("C++");
arr1.add("C++");
for (int i = 0; i < arr1.size()-1; i++) {
for (int j = i+1; j < arr1.size(); j++) {
if (arr1.get(i).equals(arr1.get(j))) {
arr1.remove(j);
j--;
}
}
}
System.out.println(arr1);
}
public static void Queue4() {
MyQueue myQueue = new MyQueue();
myQueue.add("Java");
myQueue.add("C++");
myQueue.add("Python");
myQueue.add("R");
System.out.println(myQueue);
System.out.println("---------()[28]-------");
while (!myQueue.isEmpty()) {
System.out.println(myQueue.pop());
}
System.out.println("---------()[33]-------");
System.out.println(myQueue);
}
public static void Stacktest3() {
MyStack myStack = new MyStack();
myStack.add("Java");
myStack.add("Python");
myStack.add("C++");
myStack.add("R");
System.out.println(myStack);
System.out.println("---------()[30]-------");
while (!myStack.isEmpty()) {
System.out.println(myStack.pop());
}
System.out.println("---------()[36]-------");
System.out.println(myStack);
}
public static void SimulationOfTheStackMthod2() {
//模拟栈先进后出的结构
LinkedList li = new LinkedList();
//压栈
li.addFirst("1");
li.addFirst("2");
li.addFirst("3");
li.addFirst("4");
//弹栈
System.out.println(li.removeFirst());
System.out.println(li.removeFirst());
System.out.println(li.removeFirst());
System.out.println(li.removeFirst());
}
public static void SpecificMethod1() {
LinkedList li = new LinkedList();
li.add("Java");
li.add("Python");
li.add("C++");
li.add("Go");
System.out.println(li);
li.addFirst("R");
System.out.println("---------()[24]-------");
System.out.println(li);
System.out.println("---------()[32]-------");
System.out.println(li.getFirst());
System.out.println("---------()[33]-------");
System.out.println(li.getLast());
System.out.println("---------()[36]-------");
System.out.println(li.removeFirst());
System.out.println("---------()[39]-------");
System.out.println(li.removeLast());
System.out.println("---------()[41]-------");
System.out.println(li);
}
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.HashSet;
import java.util.Objects;
public class Student {
private String name;
private Integer age;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return Objects.equals(name, student.name) &&
Objects.equals(age, student.age);
}
public String getName() {
return name;
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Student() {
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.HashSet;
import java.util.HashSet;
import java.util.Iterator;
/**
* @Class HashSetP
* @Description HashSet集合
* - void add(Object) 添加元素
* - Iterator
package com.xzy.JavaCollectionsFramWork.Code.java.util.Set;
/**
* @Class SetP
* @Description Set集合
* @Author xuzhiyong
* @DateTime 2020/6/6 0:20
* @Version 1.0
*/
public class SetP {
public static void main(String[] args) {
}
public static int getLineNumber() {
int level = 1;
StackTraceElement[] stacks = new Throwable().getStackTrace();
int lineNumber = stacks[level].getLineNumber();
return lineNumber;
}
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.LinkedHashSet;
/**
* @Class LinkedHashSetP
* @Description LinkedHashSet
* @Author xuzhiyong
* @DateTime 2020/6/6 12:02
* @Version 1.0
*/
public class LinkedHashSetP {
public static void main(String[] args) {
}
public static int getLineNumber() {
StackTraceElement[] stacks = new Throwable().getStackTrace();
int lineNumber = stacks[1].getLineNumber();
return lineNumber;
}
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.TreeSet;
import java.util.Objects;
public class Student implements Comparable{
private String name;
private Integer age;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return Objects.equals(name, student.name) &&
Objects.equals(age, student.age);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
public Student() {
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Object o) {
Student o2 = (Student) o;
//主要条件,依据Integer数值大小
int num1 = this.getAge() - o2.getAge();
//次要条件,依据name字典顺序
int num2 = num1 == 0 ? this.getName().compareTo(o2.getName()) : num1;
//次要条件,根据name的长度
int num3 = num2 == 0 ? this.getName().length() - o2.getName().length() : num2;
return num3;
}
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.TreeSet;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Objects;
public class Student1 implements Comparable {
private String name;
private Integer chineseGrade;
private Integer mathGrade;
private Integer englishGrade;
private Integer sum;
@Override
public int compareTo(Object o) {
Student1 o2 = (Student1) o;
return o2.getSum()-this.getSum();
}
@Override
public String toString() {
return "Student1{" +
"name='" + name + '\'' +
", chineseGrade=" + chineseGrade +
", mathGrade=" + mathGrade +
", englishGrade=" + englishGrade +
", sum=" + sum +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student1 student1 = (Student1) o;
return Objects.equals(name, student1.name) &&
Objects.equals(chineseGrade, student1.chineseGrade) &&
Objects.equals(mathGrade, student1.mathGrade) &&
Objects.equals(englishGrade, student1.englishGrade) &&
Objects.equals(sum, student1.sum);
}
@Override
public int hashCode() {
return Objects.hash(name, chineseGrade, mathGrade, englishGrade, sum);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getChineseGrade() {
return chineseGrade;
}
public void setChineseGrade(Integer chineseGrade) {
this.chineseGrade = chineseGrade;
}
public Integer getMathGrade() {
return mathGrade;
}
public void setMathGrade(Integer mathGrade) {
this.mathGrade = mathGrade;
}
public Integer getEnglishGrade() {
return englishGrade;
}
public void setEnglishGrade(Integer englishGrade) {
this.englishGrade = englishGrade;
}
public Integer getSum() {
return sum;
}
public Student1(String name, Integer chineseGrade, Integer mathGrade, Integer englishGrade) {
this.name = name;
this.chineseGrade = chineseGrade;
this.mathGrade = mathGrade;
this.englishGrade = englishGrade;
this.sum = chineseGrade+mathGrade+englishGrade;
}
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.TreeSet;
import java.util.Comparator;
public class StudentAgeComparator implements Comparator {
@Override
public int compare(Student o1, Student o2) {
//主要条件,依据Integer数值大小
int num1 = o1.getAge() - o2.getAge();
//次要条件,依据String字典顺序
int num2 = num1 == 0 ? o1.getName().compareTo(o2.getName()) : num1;
//次要条件,根据name的长度
int num3 = num2 == 0 ? o1.getName().length() - o2.getName().length() : num2;
return num3;
}
}
package com.xzy.JavaCollectionsFramWork.Code.java.util.TreeSet;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.TreeSet;
/**
* @Class TreeSetP
* @Description TreeSet集合, 元素唯一,可排序(自然排序、比较器排序)
* - TreeSet()构造一个新的空 set,该 set 根据其元素的自然顺序进行排序。
* - TreeSet(Collection extends E> c)构造一个包含指定 collection 元素的新 TreeSet,它
* 按照其元素的自然顺序进行排序。
* - TreeSet(Comparator super E> comparator)构造一个新的空 TreeSet,它根据指定比较器进行排序。
* - TreeSet(SortedSet s)构造一个与指定有序 set 具有相同映射关系和相同排序的新 TreeSet。
* @Author xuzhiyong
* @DateTime 2020/6/6 12:10
* @Version 1.0
*/
public class TreeSetP {
public static void main(String[] args) {
method6();
}
public static void method6() {
//测试
TreeSet student1s = new TreeSet<>();
Student1 st1 = new Student1("Tom", 10, 95, 30);
Student1 st2 = new Student1("Bill", 80, 25, 60);
Student1 st3 = new Student1("Bob", 75, 20, 90);
Student1 st4 = new Student1("Bob", 75, 20, 90);
student1s.add(st1);
student1s.add(st2);
student1s.add(st3);
student1s.add(st4);
for (Student1 s : student1s) {
System.out.println(s.getName()+"\t\t"+s.getChineseGrade()+"\t"+s.getEnglishGrade()
+"\t"+s.getMathGrade()+"\t"+s.getSum());
}
}
/**
* @Method {@link }{@link TreeSetP#method5()}T(n)=O(n)
* @Description ()和[]转化,已列出
* @Version 1.0
*/
public static void method5() {
/*
需求
1.[x,y]和(k,v)转化
(k,v)-->[k-1,v-1]或者[k+1,v+1]
[x,y]-->[x-1,y-1]或者[x+1,y+1]
分析思路
1.
注意事项
1.
*/
}
/**
* @Method {@link Void}{@link TreeSetP#method4()}T(n)=O(n)
* @Description 需求简单,逻辑思路列出
* @Version 1.0
*/
public static void method4() {
/*
需求
1.编写一个程序,获取10个[1,10]区间的随机数,要求随机数不重复。(HashSet实现)
2.键盘录入3个学生的信息(姓名、语文成绩、数学成绩、英语成绩),按照总分的高到底输出。(HashSet实现)
分析思路
1.伪代码及逻辑实现
1.1定义一个变量Integer first=0
1.2定义一个集合容器HashSet integers=new HashSet<>()
1.3逻辑部分while(first<10){integers.add((int)(Math.Random()*10+1))}
优化:1.1和1.2合并为while(integers.size()<10){...}
1.4增强for循环遍历
2.伪代码及逻辑实现
2.1定义Student1对象
2.1.1字段名称
String name;
Integer chineseGrade;
Integer mathGrade;
Integer englishGrade;
Integer sum;三门成绩之和,getSum获取值,setSum(){return 累加和}
2.2定义一个集合容器HashSet students=new HashSet<>()
2.2.1匿名内部类指定排序规则
new Comparator(Student){
@Override
public int compare(Studnet o1,Student o2){
int num1=o2.getSum-o1.getSum;
return num1;
}
}
注意事项
1.
*/
}
/**
* @Method {@link Void}{@link TreeSetP#method3}T(n)=O(n)
* @Description TreeSet自然排序,使用String中默认的字典a~z进行排序
* @Version 1.0
*/
public static void method3() {
/*
需求:
分析思路
1.创建TreeSet容器
2.添加字符串元素到1容器中
3.使用增强for遍历
注意事项
1.
*/
//1.创建TreeSet容器
TreeSet strings = new TreeSet<>();
//2.添加字符串元素到1容器中
strings.add("hello");
strings.add("Java");
strings.add("Python");
strings.add("Go");
//3.使用增强for遍历
for (String string : strings) {
System.out.println(string);
}
}
/**
* @Method {@link Void}{@link TreeSetP#method2()}T(n)=O(n)
* @Description TreeSet自然排序,自定义排序规则
* @Version 1.0
*/
public static void method2() {
/*
需求:
分析思路
1. 创建TreeSet容器
1.1排序原则:主要条件年龄大小,次要条件姓名字典顺序
1.1.1匿名内部类interface Comparator
1.1.2POJO E 实现interface Comparable
1.1.3自定义比较器实现的是interface Comparator
2. 创建Student对象
3. 将2中对象添加到1中
4. 使用增强for遍历
注意事项
1. java.lang.ClassCastException此异常是TreeSet没有实现interface Comparable
,只有实现了此接口TreeSet集合才能进行自然排序。
2.比较器是匿名内部类吗?
*/
//1. 创建TreeSet容器
//1.1排序原则:主要条件年龄大小,次要条件姓名字典顺序
//1.1.1匿名内部类
// TreeSet students = new TreeSet<>(new Comparator() {
// @Override
// public int compare(Student o1, Student o2) {
// //主要条件,依据Integer数值大小
// int num1 = o1.getAge() - o2.getAge();
// //次要条件,依据String字典顺序
// int num2 = num1 == 0 ? o1.getName().compareTo(o2.getName()) : num1;
// //次要条件,根据name的长度
// int num3 = num2 == 0 ? this.getName().length() - o2.getName().length() : num2;
// return num3;
// }
// });
//1.1.2E实现interface Compare
TreeSet students = new TreeSet<>();
//1.1.3自定义比较器
// StudentAgeComparator mycomparator = new StudentAgeComparator();
// TreeSet students = new TreeSet<>(mycomparator);
//2.创建Student对象
Student st1 = new Student("Tom", 19);
Student st2 = new Student("Bob", 20);
Student st3 = new Student("Bill", 22);
Student st4 = new Student("Robot", 18);
Student st5 = new Student("Robot", 19);
Student st6 = new Student("King", 19);
//3.将2中对象添加到1中
students.add(st1);
students.add(st2);
students.add(st3);
students.add(st4);
students.add(st5);
students.add(st6);
//4.使用增强for遍历
for (Student student : students) {
System.out.println(student.getName() + ":" + student.getAge());
}
}
public static void method1() {
TreeSet integers = new TreeSet<>();
integers.add(10);
integers.add(1);
integers.add(3);
integers.add(11);
integers.add(8);
for (Integer integer : integers) {
System.out.println(integer);
}
}
public static int getLineNumber() {
StackTraceElement[] stacks = new Throwable().getStackTrace();
int lineNumber = stacks[1].getLineNumber();
return lineNumber;
}
}
package com.xzy.javacollectionsframwork.code.java.util.map;
import java.util.Objects;
/**
* @JavaFileName Person
* @Description Person对象
* @Author xuzhiyong
* @DateTime 2020/6/8 1:20
* @Version 1.0
*/
public class Person {
private String name;
private Integer age;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Person person = (Person) o;
return Objects.equals(name, person.name) &&
Objects.equals(age, person.age);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Person() {
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
}
package com.xzy.javacollectionsframwork.code.java.util.map;
import java.util.*;
/**
* @JavaFileName MapP
* @Description Map集合
* @Author xuzhiyong
* @DateTime 2020/6/8 1:12
* @Version 1.0
*/
public class MapP {
public static void main(String[] args) {
hashMapPratice();
}
public static void hashMapPratice() {
/*
测试练习
分析思路
1.创建Person对象, 2个字段,name、age
2.生成Person的get方法、set方法、构造器,重写toString、HashCode、equals方法
3.创建变量int min=0、int max=5、int idNumberMin=100、int idNumberMax=899
int ageMin=20、int ageMax=9
4.构建随机数流Random random=new Random
5.创建Map集合存放身份证号和Person对象,HashMap maps=new HashMap<>(min)
6.创建Set集合存放Person对象,HashSet persons=new HashSet<>(min)
7.创建Set集合idNumbers存放idNumber,HashSet idNumbers=new HashSet<>(min)
8.使用while循环生成Person对象,并将Person对象存放进persons
while(persons.size() maps=new HashMap<>(min)
HashMap maps = new HashMap<>(min);
//6.创建Set集合存放Person对象,HashSet persons=new HashSet<>(min)
HashSet persons = new HashSet<>(min);
//7.创建Set集合idNumbers存放idNumber,HashSet idNumbers=new HashSet<>(min)
HashSet idNumbers = new HashSet<>(min);
//8.使用while循环生成Person对象,并将Person对象存放进persons
//while(persons.size() ids = maps.keySet();
for (String idNumber : ids) {
Person person = maps.get(idNumber);
String print = idNumber + ":" + person.getName() + ":" + person.getAge();
System.out.println(print);
}
}
/**
* HashMap练习entrySet遍历
*
* @return、parameters、type、T(n) {@link Void}{@link MapP#methodEntrySet()}O(n)
* @Version 1.0
*/
public static void methodEntrySet() {
/*
HashMap练习entrySet遍历
分析思路
1.定义方法常量Integer start=0、Integer end=10
2.创建Map集合,HashMap maps=new HashMap()
3.创建integers数组,Integer[] integers=new Integer[10]
4.创建strings数组,String[] strings=new String[10]
5.使用for循环添加元素到integers,for(i=start,i maps=new HashMap<>()
HashMap maps = new HashMap<>(start);
//3.创建integers数组,Integer[] integers=new Integer[10]
Integer[] integers = new Integer[10];
//4.创建strings数组,String[] strings=new String[10]
String[] strings = new String[10];
//5.使用for循环添加元素到integers,for(i=start,i> entries = maps.entrySet();
for (Map.Entry entry : entries) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
/**
* HashMap练习keySet遍历
*
* @return、parameters、type、T(n) {@link Void}{@link MapP#methodKeySet()}O(n)
* @Version 1.0
*/
public static void methodKeySet() {
/*
测试练习
分析思路
1.定义方法常量Integer start=0、Integer end=10
2.创建Map集合,HashMap maps=new HashMap()
3.创建integers数组,Integer[] integers=new Integer[10]
4.创建strings数组,String[] strings=new String[10]
5.使用for循环添加元素到integers,for(i=start,i maps=new HashMap<>()
HashMap maps = new HashMap<>(start);
//3.创建integers数组,Integer[] integers=new Integer[10]
Integer[] integers = new Integer[10];
//4.创建strings数组,String[] strings=new String[10]
String[] strings = new String[10];
//5.使用for循环添加元素到integers,for(i=start,i keys = maps.keySet();
for (Integer key : keys) {
String value = maps.get(key);
System.out.println(key + ":" + value);
}
}
public static void method() {
/**
测试练习
- V put(K key, V value)将指定的值与此映射中的指定键关联(可选操作)。
- void putAll(map extends K,? extends V> m)从指定映射中将所有映射关系复制到此映射中(可选操作)。
- void clear()从此映射中移除所有映射关系(可选操作)。
- V remove(object key)如果存在一个键的映射关系,则将其从此映射中移除(可选操作)。
- boolean containsKey(object key)如果此映射包含指定键的映射关系,则返回 true。
- boolean containsValue(object value)如果此映射将一个或多个键映射到指定值,则返回 true。
- V get(object key)返回指定键所映射的值;如果此映射不包含该键的映射关系,则返回 null。
- set keySet()返回此映射中包含的键的 set 视图。
- collection values()返回此映射中包含的值的 collection 视图。
- set> entrySet()返回此映射中包含的映射关系的 set 视图。
注意事项
1.put方法首次添加一个集合中没有的key、value时返回null,添加相同
key、value时,其中value会覆盖原先的key对应的value,并返回原
集合中的value。
2.remove一个key时,key如何存在,返回key对应的value,key如果
不存在,返回null
3.map.Entry,Entry中文是实体,属于public interface map
的内部接口interface map,是一个Set集合,包含键值对。
4.Map集合的遍历方式
4.1得到entrySet集合,然后通过getKey和getValue得到键和值
4.2得到keySet集合,然后通过key找value
*/
HashMap language = new HashMap<>(1);
language.put("Java", String.valueOf(System.currentTimeMillis()));
language.put("Go", String.valueOf(System.currentTimeMillis()));
language.put("R", String.valueOf(System.currentTimeMillis()));
language.put("Python", String.valueOf(System.currentTimeMillis()));
language.put("Python", String.valueOf(System.currentTimeMillis()));
System.out.println("---------(列表)[" + getLineNumber() + "]-------");
Set keys = language.keySet();
for (String key : keys) {
String value = language.get(key);
System.out.println(key + ":" + value);
}
System.out.println("---------(get)[" + getLineNumber() + "]-------");
System.out.println(language.get("Java"));
System.out.println("---------(value)[" + getLineNumber() + "]-------");
System.out.println(language.values());
System.out.println("---------(keySet)[" + getLineNumber() + "]-------");
System.out.println(language.keySet());
System.out.println("---------(entrySet)[" + getLineNumber() + "]-------");
System.out.println(language.entrySet());
System.out.println("---------(entry)[" + getLineNumber() + "]-------");
Set> entries = language.entrySet();
for (Map.Entry entry : entries) {
String s = entry.setValue("---");
System.out.println(s);
}
Set> entries1 = language.entrySet();
for (Map.Entry stringStringEntry : entries1) {
System.out.println(stringStringEntry.getKey() + ":" + stringStringEntry.getValue());
}
System.out.println("---------()[" + getLineNumber() + "]-------");
System.out.println(language.containsKey("Java"));
System.out.println(language.containsKey("Java+"));
System.out.println("---------()[" + getLineNumber() + "]-------");
System.out.println(language.containsValue("1591506039719"));
System.out.println("---------()[" + getLineNumber() + "]-------");
System.out.println(language.remove("R+"));
System.out.println(language);
System.out.println("---------()[" + getLineNumber() + "]-------");
language.clear();
System.out.println(language.size());
}
/**
* 获得当前行号
*
* @return、parameters、type、T(n) {@link Void}{@link MapP#getLineNumber()}O(n)
* @Version 1.0
*/
public static int getLineNumber() {
StackTraceElement[] stacks = new Throwable().getStackTrace();
int lineNumber = stacks[1].getLineNumber();
return lineNumber;
}
}
package com.xzy.javacollectionsframwork.code.java.util.LinkedHashMap;
import java.util.Objects;
/**
* @JavaFileName Person
* @Description Person对象
* @Author xuzhiyong
* @DateTime 2020/6/8 1:20
* @Version 1.0
*/
public class Person {
private String name;
private Integer age;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Person person = (Person) o;
return Objects.equals(name, person.name) &&
Objects.equals(age, person.age);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Person() {
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
}
package com.xzy.javacollectionsframwork.code.java.util.LinkedHashMap;
import java.util.LinkedHashMap;
import java.util.Set;
/**
* @JavaFileName LinkedHashMapP
* @Description
* @Author xuzhiyong
* @DateTime 2020/6/8 16:23
* @Version 1.0
*/
public class LinkedHashMapP {
public static void main(String[] args) {
}
/**
* 方法说明
*
* @return {@link Void}
* @parameterType {@link LinkedHashMapP#linkedHashMapPratice()}
* @Version 1.0
*/
public static void linkedHashMapPratice() {
LinkedHashMap lmaps = new LinkedHashMap<>(0);
Person p1 = new Person("xzy", 12);
Person p2 = new Person("xzy", 12);
Person p3 = new Person("xzy", 12);
Person p4 = new Person("xzy", 12);
lmaps.put("001", p1);
lmaps.put("002", p2);
lmaps.put("003", p3);
lmaps.put("004", p4);
Set strings = lmaps.keySet();
for (String string : strings) {
Person person = lmaps.get(string);
System.out.println(string + ":" + person.getName() + "::" + person.getAge());
}
}
/**
* 方法说明
*
* @return {@link Integer}
* @parameterType {@link LinkedHashMapP#getLineNumber()}
* @Version 1.0
*/
public static int getLineNumber() {
StackTraceElement[] stacks = new Throwable().getStackTrace();
int lineNumber = stacks[1].getLineNumber();
return lineNumber;
}
}
package com.xzy.javacollectionsframwork.code.java.util.treemap;
import java.util.Objects;
/**
* @JavaFileName Person
* @Description Person对象
* @Author xuzhiyong
* @DateTime 2020/6/8 1:20
* @Version 1.0
*/
public class Person {
private String name;
private Integer age;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// Person person = (Person) o;
// return Objects.equals(name, person.name) &&
// Objects.equals(age, person.age);
// }
// @Override
// public int hashCode() {
// return Objects.hash(name, age);
// }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Person() {
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
}
package com.xzy.javacollectionsframwork.code.java.util.treemap;
import java.util.Comparator;
/**
* @JavaFileName Person
* @Description Person对象
* @Author xuzhiyong
* @DateTime 2020/6/8 1:20
* @Version 1.0
*/
public class PersonComparator implements Comparator {
@Override
public int compare(Person o1, Person o2) {
//主要条件,依据Integer数值大小
int num1 = o1.getAge() - o2.getAge();
//次要条件,依据String字典顺序
int num2 = num1 == 0 ? o1.getName().compareTo(o2.getName()) : num1;
//次要条件,根据name的长度
int num3 = num2 == 0 ? o1.getName().length() - o2.getName().length() : num2;
return num3;
}
}
package com.xzy.javacollectionsframwork.code.java.util.treemap;
import java.util.Comparator;
/**
* @JavaFileName Person
* @Description Person对象
* @Author xuzhiyong
* @DateTime 2020/6/8 1:20
* @Version 1.0
*/
public class PersonImpl implements Comparable {
private String name;
private Integer age;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// Person person = (Person) o;
// return Objects.equals(name, person.name) &&
// Objects.equals(age, person.age);
// }
// @Override
// public int hashCode() {
// return Objects.hash(name, age);
// }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public PersonImpl() {
}
public PersonImpl(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(PersonImpl o) {
PersonImpl o2 = (PersonImpl) o;
//主要条件,依据Integer数值大小
int num1 = this.getAge() - o2.getAge();
//次要条件,依据String字典顺序
int num2 = num1 == 0 ? this.getName().compareTo(o2.getName()) : num1;
//次要条件,根据name的长度
int num3 = num2 == 0 ? this.getName().length() - o2.getName().length() : num2;
return num3;
}
}
package com.xzy.javacollectionsframwork.code.java.util.treemap;
import java.util.*;
/**
* @JavaFileName TreeMapP
* @Description
* @Author xuzhiyong
* @DateTime 2020/6/8 16:51
* @Version 1.0
*/
public class TreeMapP {
public static void main(String[] args) {
method7();
}
/**
* 统计String中某个char出现的次数,并可以使用字典顺序排序
*
* @return {@link Void}
* @parameterType {@link TreeMapP#}
* @Version 1.0
*/
public static void method7() {
String str = "adfqqdqwfwfrtyrterqwdw";
char[] chs = str.toCharArray();
TreeMap treeMap = new TreeMap<>();
for (char c : chs) {
Integer num = treeMap.get(c);
if (num == null) {
treeMap.put(c, 1);
} else {
num++;
treeMap.put(c, num);
}
}
StringBuffer sb = new StringBuffer();
Set keys = treeMap.keySet();
for (Character key : keys) {
Integer value = treeMap.get(key);
//链式编程
sb.append(key).append("(").append(value).append(")");
}
System.out.println(sb);
}
/**
* HashMap集合嵌套HashMap练习,插入序号
*
* @return {@link Void}
* @parameterType {@link TreeMapP#}
* @Version 1.0
*/
public static void method6() {
int initialization = 0;
HashMap sgyy = new HashMap<>(initialization);
HashMap sdxl = new HashMap<>(initialization);
HashMap xajh = new HashMap<>(initialization);
HashMap sgyyN = new HashMap<>(initialization);
HashMap sdxlN = new HashMap<>(initialization);
HashMap xajhN = new HashMap<>(initialization);
sgyy.put("周瑜", "小乔");
sgyy.put("吕布", "貂蝉");
sdxl.put("郭靖", "黄蓉");
sdxl.put("杨过", "小龙女");
xajh.put("令狐冲", "任盈盈");
xajh.put("林平之", "岳灵珊");
sgyyN.put("1", "三国演义");
sdxlN.put("2", "神雕侠侣");
xajhN.put("3", "笑傲江湖");
HashMap, HashMap> books = new HashMap<>(initialization);
books.put(sgyyN, sgyy);
books.put(sdxlN, sdxl);
books.put(xajhN, xajh);
System.out.println("---------()[" + getLineNumber() + "]-------");
//加入序号,勉强完整
Set> hashMaps = books.keySet();
for (HashMap hashMap : hashMaps) {
Set numbers = hashMap.keySet();
for (String number : numbers) {
System.out.println("这是第" + number + "本书" + hashMap.get(number));
HashMap persons = books.get(hashMap);
Set lefts = persons.keySet();
for (String left : lefts) {
System.out.println(left + ":::" + persons.get(left));
}
}
}
}
/**
* ArrayList中嵌套HashMap练习entrySet遍历,加入索引
*
* @return {@link Void}
* @parameterType {@link TreeMapP#}
* @Version 1.0
*/
public static void method5() {
int initialization = 0;
HashMap sgyy = new HashMap<>(initialization);
HashMap sdxl = new HashMap<>(initialization);
HashMap xajh = new HashMap<>(initialization);
ArrayList xs = new ArrayList<>();
sgyy.put("周瑜", "小乔");
sgyy.put("吕布", "貂蝉");
sdxl.put("郭靖", "黄蓉");
sdxl.put("杨过", "小龙女");
xajh.put("令狐冲", "任盈盈");
xajh.put("林平之", "岳灵珊");
xs.add(sgyy);
xs.add(sdxl);
xs.add(xajh);
//加入序号,勉强完整
for (int i = 0; i < xs.size(); i++) {
HashMap hashMaps = xs.get(i);
Set set = hashMaps.entrySet();
System.out.println(i + 1);
for (Map.Entry entry : set) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
}
/**
* 实现Comparable接口比较
*
* @return {@link Void}
* @parameterType {@link TreeMapP#}
* @Version 1.0
*/
public static void method4() {
//TreeMap集合去重和排序依靠的是两个键比较,大放右,小放左,一样不添加元素,故
//不需要重写equals和hashCode方法
TreeMap tmaps = new TreeMap<>();
PersonImpl p1 = new PersonImpl("Tom", 19);
PersonImpl p2 = new PersonImpl("Bob", 22);
PersonImpl p3 = new PersonImpl("Bill", 15);
PersonImpl p4 = new PersonImpl("bill", 10);
tmaps.put(p1, "001");
tmaps.put(p2, "001");
tmaps.put(p3, "001");
tmaps.put(p4, "001");
Set PersonImpls = tmaps.keySet();
for (PersonImpl PersonImpl : PersonImpls) {
String value = tmaps.get(PersonImpl);
System.out.println(PersonImpl.getName() + ":" + PersonImpl.getAge() + ":" + value);
}
}
/**
* 自定义比较器进行比较
*
* @return {@link Void}
* @parameterType {@link TreeMapP#}
* @Version 1.0
*/
public static void method3() {
//TreeMap集合去重和排序依靠的是两个键比较,大放右,小放左,一样不添加元素,故
//不需要重写equals和hashCode方法
PersonComparator personComparator = new PersonComparator();
TreeMap tmaps = new TreeMap<>(personComparator);
Person p1 = new Person("Tom", 19);
Person p2 = new Person("Bob", 22);
Person p3 = new Person("Bill", 15);
Person p4 = new Person("bill", 10);
tmaps.put(p1, "001");
tmaps.put(p2, "001");
tmaps.put(p3, "001");
tmaps.put(p4, "001");
Set persons = tmaps.keySet();
for (Person person : persons) {
String value = tmaps.get(person);
System.out.println(person.getName() + ":" + person.getAge() + ":" + value);
}
}
/**
* 匿名内部类进行比较
*
* @return {@link Void}
* @parameterType {@link TreeMapP#}
* @Version 1.0
*/
public static void method2() {
//TreeMap集合去重和排序依靠的是两个键比较,大放右,小放左,一样不添加元素,故
//不需要重写equals和hashCode方法
TreeMap tmaps = new TreeMap<>(new Comparator() {
@Override
public int compare(Person o1, Person o2) {
//主要条件,依据Integer数值大小
int num1 = o1.getAge() - o2.getAge();
//次要条件,依据String字典顺序
int num2 = num1 == 0 ? o1.getName().compareTo(o2.getName()) : num1;
//次要条件,根据name的长度
int num3 = num2 == 0 ? o1.getName().length() - o2.getName().length() : num2;
return num3;
}
});
Person p1 = new Person("Tom", 19);
Person p2 = new Person("Bob", 22);
Person p3 = new Person("Bill", 15);
Person p4 = new Person("bill", 10);
tmaps.put(p1, "001");
tmaps.put(p2, "001");
tmaps.put(p3, "001");
tmaps.put(p4, "001");
Set persons = tmaps.keySet();
for (Person person : persons) {
String value = tmaps.get(person);
System.out.println(person.getName() + ":" + person.getAge() + ":" + value);
}
}
/**
* 方法说明
*
* @return {@link Void}
* @parameterType {@link TreeMapP#}
* @Version 1.0
*/
public static void method1() {
//Integer实现了自然排序,key会按照从小到大的顺序进行排列
TreeMap tmaps = new TreeMap<>();
tmaps.put(20, "xzy");
tmaps.put(18, "Bob");
tmaps.put(19, "Tom");
tmaps.put(21, "Bill");
Set integers = tmaps.keySet();
for (Integer key : integers) {
String value = tmaps.get(key);
System.out.println(key + ":" + value);
}
}
/**
* 获得当前行号
*
* @return {@link Integer}
* @parameterType {@link TreeMapP#getLineNumber()}
* @Version 1.0
*/
public static int getLineNumber() {
StackTraceElement[] stacks = new Throwable().getStackTrace();
int lineNumber = stacks[1].getLineNumber();
return lineNumber;
}
}
package com.xzy.javacollectionsframwork.code.java.util.hashtable;
import java.util.Hashtable;
/**
* @JavaFileName HashtableP
* @Description
* @Author xuzhiyong
* @DateTime 2020/6/9 1:55
* @Version 1.0
*/
public class HashtableP {
public static void main(String[] args) {
}
/**
* Hashtable集合中不允许出现null
*
* @return {@link Void}
* @parameterType {@link HashtableP#method1()}
* @Version 1.0
*/
public static void method1() {
Hashtable map = new Hashtable<>();
}
/**
* 获得当前行号
*
* @return {@link Integer}
* @parameterType {@link HashtableP#getLineNumber()}
* @Version 1.0
*/
public static int getLineNumber() {
StackTraceElement[] stacks = new Throwable().getStackTrace();
int lineNumber = stacks[1].getLineNumber();
return lineNumber;
}
}
package com.xzy.javacollectionsframwork.code.java.util.collections;
/**
* @JavaFileName Person
* @Description Person对象
* @Author xuzhiyong
* @DateTime 2020/6/8 1:20
* @Version 1.0
*/
public class PersonImpl implements Comparable {
private String name;
private Integer age;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public PersonImpl() {
}
public PersonImpl(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(PersonImpl o) {
//注意主要条件
int num1 = this.age - o.age;
//次要条件
int num2 = num1 == 0 ? this.name.compareTo(o.name) : num1;
return num2;
}
}
package com.xzy.javacollectionsframwork.code.java.util.collections;
import java.util.Comparator;
/**
* @JavaFileName Person
* @Description Person对象
* @Author xuzhiyong
* @DateTime 2020/6/8 1:20
* @Version 1.0
*/
public class PersonComparator implements Comparator {
@Override
public int compare(Person o1, Person o2) {
//主要条件,依据Integer数值大小
int num1 = o1.getAge() - o2.getAge();
//次要条件,依据String字典顺序
int num2 = num1 == 0 ? o1.getName().compareTo(o2.getName()) : num1;
//次要条件,根据name的长度
int num3 = num2 == 0 ? o1.getName().length() - o2.getName().length() : num2;
return num3;
}
}
package com.xzy.javacollectionsframwork.code.java.util.collections;
/**
* @JavaFileName Person
* @Description Person对象
* @Author xuzhiyong
* @DateTime 2020/6/8 1:20
* @Version 1.0
*/
public class Person {
private String name;
private Integer age;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Person() {
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
}
package com.xzy.javacollectionsframwork.code.java.util.collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* @JavaFileName CollectionsP
* @Description
* @Author xuzhiyong
* @DateTime 2020/6/9 2:13
* @Version 1.0
*/
public class CollectionsP {
public static void main(String[] args) {
method5();
}
/**
* PersonImpl实现Comarable,然后使用Collections.sort
* 进行对象普通查找、二分查找
*
* @return {@link Void}
* @parameterType {@link CollectionsP#}
* @Version 1.0
*/
public static void method5() {
//不会去重,比较器优先级最高
ArrayList personsList = new ArrayList<>();
PersonImpl p1 = new PersonImpl("xzy", 20);
PersonImpl p2 = new PersonImpl("Tom", 18);
PersonImpl p3 = new PersonImpl("Bob", 30);
PersonImpl p4 = new PersonImpl("Bill", 25);
personsList.add(p1);
personsList.add(p2);
personsList.add(p3);
personsList.add(p4);
System.out.println("---------()[" + getLineNumber() + "]-------");
Collections.sort(personsList);
for (PersonImpl person : personsList) {
System.out.println(person);
}
System.out.println("---------()[" + getLineNumber() + "]-------");
/**
* 二分查找,对象字段需要先排序,然后查找,如果不排序,会将对象的未排序
* 索引打印
*/
int i = Collections.binarySearch(personsList, p3);
System.out.println(i);
//以比较器规定的对象主要条件进行Max求取
PersonImpl max = Collections.max(personsList);
System.out.println(max);
//反转对象
System.out.println("---------()[" + getLineNumber() + "]-------");
Collections.reverse(personsList);
for (PersonImpl person : personsList) {
System.out.println(person);
}
//洗牌
System.out.println("---------()[" + getLineNumber() + "]-------");
Collections.shuffle(personsList);
for (PersonImpl person : personsList) {
System.out.println(person);
}
}
/**
* PersonImpl实现Comarable,然后使用Collections.sort进行排序
*
* @return {@link Void}
* @parameterType {@link CollectionsP#}
* @Version 1.0
*/
public static void method2() {
//不会去重,比较器优先级最高
ArrayList personsList = new ArrayList<>();
PersonImpl p1 = new PersonImpl("xzy", 20);
PersonImpl p2 = new PersonImpl("Tom", 18);
PersonImpl p3 = new PersonImpl("Bob", 30);
PersonImpl p4 = new PersonImpl("Bill", 25);
personsList.add(p1);
personsList.add(p2);
personsList.add(p3);
personsList.add(p4);
Collections.sort(personsList);
for (PersonImpl person : personsList) {
System.out.println(person);
}
}
/**
* 设计比较器PersonComparator,然后使用Collections.sort进行排序
*
* @return {@link Void}
* @parameterType {@link CollectionsP#}
* @Version 1.0
*/
public static void method3() {
//不会去重,比较器优先级最高
PersonComparator personComparator = new PersonComparator();
ArrayList personsList = new ArrayList<>();
Person p1 = new Person("xzy", 20);
Person p2 = new Person("Tom", 18);
Person p3 = new Person("Bob", 30);
Person p4 = new Person("Bill", 25);
personsList.add(p1);
personsList.add(p2);
personsList.add(p3);
personsList.add(p4);
Collections.sort(personsList, personComparator);
for (Person person : personsList) {
System.out.println(person);
}
}
/**
* 匿名内部类规定排序规则,然后使用Collections.sort进行排序
*
* @return {@link Void}
* @parameterType {@link CollectionsP#}
* @Version 1.0
*/
public static void method4() {
//不会去重,比较器优先级最高
ArrayList personsList = new ArrayList<>();
Person p1 = new Person("xzy", 20);
Person p2 = new Person("Tom", 18);
Person p3 = new Person("Bob", 30);
Person p4 = new Person("Bill", 25);
personsList.add(p1);
personsList.add(p2);
personsList.add(p3);
personsList.add(p4);
Collections.sort(personsList, new Comparator() {
@Override
public int compare(Person o1, Person o2) {
//主要条件,依据Integer数值大小
int num1 = o1.getAge() - o2.getAge();
//次要条件,依据String字典顺序
int num2 = num1 == 0 ? o1.getName().compareTo(o2.getName()) : num1;
//次要条件,根据name的长度
int num3 = num2 == 0 ? o1.getName().length() - o2.getName().length() : num2;
return num3;
}
});
for (Person person : personsList) {
System.out.println(person);
}
}
/**
* Collections构造方法测试练习
*
* @return {@link Void}
* @parameterType {@link CollectionsP#}
* @Version 1.0
*/
public static void method1() {
/*
Collections成员方法
- public static void sort(List list)默认情况下是自然排序
- public static int binarySearch(List> list,T key)二分查找
- public static T max(Collection<> oll)最大值
- public static void reverse(List> list)反转
- public static void shuffle(List> list)随机置换
注意事项
1.用sort方法对list集合进行排序,list集合中的元素自身要有比较性
2.二分查找的元素自身必须具有比较性,集合必须有序,如果找到了返回索引,如果没找到
返回负数
*/
ArrayList list = new ArrayList<>();
list.add(10);
list.add(9);
list.add(8);
list.add(3);
list.add(15);
System.out.println(list);
//public static void sort(List list)默认情况下是自然排序
Collections.sort(list);
System.out.println(list);
//public static int binarySearch(List> list,T key)二分查找
int i = Collections.binarySearch(list, 3);
System.out.println(i);
//public static T max(Collection<> oll)最大值
Integer max = Collections.max(list);
System.out.println(max);
//public static void reverse(List> list)反转
Collections.reverse(list);
System.out.println(list);
//public static void shuffle(List> list)随机置换
Collections.shuffle(list);
System.out.println(list);
}
/**
* 获得当前行号
*
* @return {@link Integer}
* @parameterType {@link CollectionsP#getLineNumber()}
* @Version 1.0
*/
public static int getLineNumber() {
StackTraceElement[] stacks = new Throwable().getStackTrace();
int lineNumber = stacks[1].getLineNumber();
return lineNumber;
}
}