集合
List也叫“动态数组”(长度可变)
package com.www.java2;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
/**
*1.集合概述
* 存储针对是内存存储,而不是持久化存储
*2.Collection接口中方法使用
*
*
* @author www
* @creat 2022-{MONTH}-{DAY}
*/
public class CollectionTest {
@Test
public void test(){
Collection coll = new ArrayList();
//add(Object e)
coll.add("AA");
coll.add("BB");
coll.add("123");//自动装箱
coll.add(new Date());
//size()
System.out.println(coll.size());//4
//addAll(Collection c)
Collection coll1 = new ArrayList();
coll1.add("CC");
coll1.add("DD");
coll.addAll(coll1);
System.out.println(coll.size());//6
//clear();清空集合元素
coll.clear();
//isEmpty();判断集合中是否有元素
System.out.println(coll.isEmpty());//true
}
}
package com.www.java;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* @author www
* @creat 2022-{MONTH}-{DAY}
*/
public class CollectionTest {
@Test
public void test(){
Collection coll = new ArrayList();
coll.add(123);//自动装箱
coll.add(new String("Tom"));
coll.add(new Person("Jerry",23));
coll.add(false);//自动类型提升
//contains(Object obj):判断当前集合中是否包含obj
//调用时会调用obj对象所在类的equals方法(自定义类需要重写)
System.out.println(coll.contains("Tom"));//True
System.out.println(coll.contains(new Person("Jerry", 23)));//True(自己重写了,如果不重写,equals和==一样)
System.out.println(coll.contains(new String("Tom")));//True(String类重写了equals方法)
//containsAll(Collection coll1):判断coll1的所有元素是否都存在于当前集合中
Collection coll1 = Arrays.asList(123,"Tom",false);
System.out.println(coll.containsAll(coll1));//true
}
@Test
public void test1(){
Collection coll = new ArrayList();
coll.add(123);//自动装箱
coll.add(456);
coll.add(456);
coll.add(new String("Tom"));
coll.add(new Person("Jerry",23));
coll.add(false);//自动类型提升
//remove(Object obj):也会用equals比较
coll.remove(123);//有返回值,可以不接收
//removeAll(Coolection coll1):移除共有元素
Collection coll1 = Arrays.asList(456,234);
System.out.println(coll);
coll.removeAll(coll1);
System.out.println(coll);
}
/*
[456, 456, Tom, Person{name='Jerry', age=23}, false]
调用euqals方法
调用euqals方法
[Tom, Person{name='Jerry', age=23}, false]
*/
@Test
public void test2(){
Collection coll = new ArrayList();
coll.add(123);//自动装箱
coll.add(456);
coll.add(456);
coll.add(new String("Tom"));
coll.add(new Person("Jerry",23));
coll.add(false);//自动类型提升
//retainAll(Object obj):交集,修改了当前集合
Collection coll1 = Arrays.asList(456,234);
System.out.println(coll);
coll.retainAll(coll1);
System.out.println(coll);
}
/*
[123, 456, 456, Tom, Person{name='Jerry', age=23}, false]
调用euqals方法
调用euqals方法
[456, 456]
*/
@Test
public void test3(){
Collection coll = new ArrayList();
coll.add(123);//自动装箱
coll.add(456);
coll.add(456);
coll.add(new String("Tom"));
coll.add(new Person("Jerry",23));
coll.add(false);//自动类型提升
Collection coll1 = new ArrayList();
coll1.add(456);
coll1.add(123);//自动装箱
coll1.add(456);
coll1.add(new String("Tom"));
coll1.add(new Person("Jerry",23));
coll1.add(false);//自动类型提升
//equals(Object obj)
System.out.println(coll.equals(coll1));//false.因为ArrayList是有序的
}
@Test
public void test4(){
Collection coll = new ArrayList();
coll.add(123);//自动装箱
coll.add(456);
coll.add(456);
coll.add(new String("Tom"));
coll.add(new Person("Jerry",23));
coll.add(false);//自动类型提升
//hashCode():返回当前对象的哈希值
System.out.println(coll.hashCode());
//集合---->数组:toArray()
Object[] arr = coll.toArray();
for (int i = 0; i < arr.length;i++){
System.out.println(arr[i]);
}
//拓展:数组---->集合
List<String> list = Arrays.asList(new String[]{"123", "234", "hahaha"});
System.out.println(list);//[123, 234, hahaha]
List arr1 = Arrays.asList(new int[]{123, 456});
System.out.println(arr1);//[[I@a74868d]:将上面的数组看成了一个元素
//!!!!!!!!!!!!!!!!学完反射再来看
List arr2 = Arrays.asList(new Integer[]{123, 456});
System.out.println(arr2);//[123, 456]
//iterator():返回Iterat实例,用于遍历集合元素,放在IteratorTest.java测试
}}
有一部分学完反射再看
package com.www.java;
/**
* @author www
* @creat 2022-{MONTH}-{DAY}
*/
public class Person implements Comparable{
String name;
int age;
public Person() {
}
public Person(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 "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
System.out.println("调用euqals方法");
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
if (age != person.age) return false;
return name.equals(person.name);
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + age;
return result;
}
//按照姓名从小到大排列
@Override
public int compareTo(Object o) {
System.out.println("调用compareTo方法");
if(o.getClass() == getClass()){
Person p = (Person)o;
return this.name.compareTo(p.name);
}else{
throw new RuntimeException("输入类型不匹配");
}
}
}
迭代器
package com.www.java;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* 集合元素的遍历,使用迭代器Iterator接口
* @author www
* @creat 2022-{MONTH}-{DAY}
*/
public class IteratorTest {
@Test
public void test(){
Collection coll = new ArrayList();
coll.add(123);//自动装箱
coll.add(456);
coll.add(456);
coll.add(new String("Tom"));
coll.add(new Person("Jerry",23));
coll.add(false);//自动类型提升
Iterator arr = coll.iterator();
// //方式一
// System.out.println(arr.next());//123
// System.out.println(arr.next());//456
// System.out.println(arr.next());//456
// System.out.println(arr.next());//Tom
// System.out.println(arr.next());//Person{name = 'Jerry',age=23}
// System.out.println(arr.next());//false
// System.out.println(arr.next());//NoSuchElementException
// //方式二:不推荐
// for(int i = 0;i < coll.size();i++){
// System.out.println(arr.next());
// }
//方式三:推荐
while(arr.hasNext()){
System.out.println(arr.next());
}
}
//remove(),迭代器中的,并非集合中的remove()
@Test
public void test1(){
Collection coll = new ArrayList();
coll.add(123);//自动装箱
coll.add(456);
coll.add(456);
coll.add(new String("Tom"));
coll.add(new Person("Jerry",23));
coll.add(false);//自动类型提升
Iterator arr = coll.iterator();
while(arr.hasNext()){
Object obj = arr.next();
if("Tom".equals(obj)){//最好Tom,否则万一obj是null,就出错了
arr.remove();//先调用next再调用remove()
}
}
Iterator iterator = coll.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
foreach
package com.www.java;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
/**
* JDK5.0新增增强for循环,
* @author www
* @creat 2022-{MONTH}-{DAY}
*/
public class ForTest {
@Test
public void test(){
Collection coll = new ArrayList();
coll.add(123);//自动装箱
coll.add(456);
coll.add(456);
coll.add(new String("Tom"));
coll.add(new Person("Jerry",23));
coll.add(false);//自动类型提升
//for(集合元素类型 变量名:集合对象)
//内部仍然调用迭代器
for(Object obj:coll){
System.out.println(obj);
}
}
@Test
public void test2(){
int[] arr = new int[]{1,2,3,4,5};
//for(数组元素类型 变量名:数组对象)
for(int i:arr){
System.out.println(i);
}
}
@Test
public void test3(){
String[] arr = new String[]{"123","Tom"};
for(String arr1:arr){
arr1 = "haha";
}
for(String arr1:arr){
System.out.println(arr1);//并不改变,arr1属于新的变量
}
}
}
List接口
package com.www.java;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* 1.Collection接口
* --->List接口
* ------>ArrayList类:list接口主要实现类,线程不安全,效率高,底层使用Object[]存储
* ------>LinkedList类:底层使用双向链表存储,对于频繁的插入、删除操作,效率高
* ------>Vector类:list接口古老实现类,线程安全,效率低,底层使用Object[]存储
*
*2. Arraylist、LinkList、Vector三者比较
* 同:都实现了list接口,储存数据特点相同(可重复,有序)
* 不同:见上
*3.list接口中的常用方法
*
*
* @author www
* @creat 2022-{MONTH}-{DAY}
*/
public class ListTest {
@Test
public void test2(){
ArrayList coll = new ArrayList();
coll.add(123);//自动装箱
coll.add(456);
coll.add(456);
coll.add(new String("Tom"));
coll.add(new Person("Jerry",23));
coll.add(false);//自动类型提升
Iterator iter = coll.iterator();
//方式一
System.out.println(iter.next());
System.out.println(iter.next());
System.out.println(iter.next());
System.out.println(iter.next());
System.out.println(iter.next());
System.out.println(iter.next());
//方式二
for(Object obj:coll){
System.out.println(obj);
}
//方式三
for(int i = 0;i < coll.size();i++){
System.out.println(coll.get(i));
}
//方式三
Iterator iter1 = coll.iterator();
while(iter1.hasNext()){
System.out.println(iter1.next());
}
}
@Test
public void test1(){
ArrayList coll = new ArrayList();
coll.add(123);//自动装箱
coll.add(456);
coll.add(456);
coll.add(new String("Tom"));
coll.add(new Person("Jerry",23));
coll.add(false);//自动类型提升
//int indexOf(Object obj):返回首次出现obj的位置,若没有返回-1
System.out.println(coll.indexOf(123));
//int lastIndexOf(Object obj):返回最后一次出现obj的位置,若没有返回-1
System.out.println(coll.lastIndexOf(456));
//Object remove(int index):移除指定位置元素,并返回此元素
System.out.println(coll.remove(2));
System.out.println(coll);
//Object set(int index,Object ele):指定位置的元素设置为ele
coll.set(1,234);
System.out.println(coll);
//List sublist(int fromIndex,int toIndex):返回从fromIndex到toIndex位置的子集,左闭右开
System.out.println(coll.subList(1, 3));
System.out.println(coll);
}
@Test
public void test(){
ArrayList coll = new ArrayList();
coll.add(123);//自动装箱
coll.add(456);
coll.add(456);
coll.add(new String("Tom"));
coll.add(new Person("Jerry",23));
coll.add(false);//自动类型提升
//void add(int index,Object ele):在index位置插入元素ele
coll.add(1,"hello");
System.out.println(coll);
//boolean addAll(int index,Collection eles):在index位置插入集合eles
List arr = Arrays.asList(1, 2, 3);
coll.addAll(1,arr);
System.out.println(coll);
//Object get(int index)
System.out.println(coll.get(0));
}
}
Set接口
package com.www.java2;
import com.www.java.Person;
import org.junit.Test;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
/**
*
* 1.Set接口:没有额外定义新的方法,使用的都是其父类Coolection的方法
* 说明:存储无序、不可重复数据,要求向Set存储数据,一定要重写hashCode()和equals(),且重写的这两个方法要尽可能保持一致性
* (相等的对象具有相等的散列码)(技巧:对象中用来比较的属性,都参与到计算哈希值中)
* ----->HashSet类:Set主要实现类,线程不安全,可以存储null值
* ----->LinkedHashSet类:HashSet子类,遍历其内部数据时,可以按照添加顺序遍历
* ----->TreeSet:红黑树存储,元素要求同一类,可以按照添加元素指定属性进行排序
*
* @author www
* @creat 2022-{MONTH}-{DAY}
*/
public class SetTest {
/*一、Set接口:存储无序、不可重复数据
以HashSet为例
1.无序性:不等于随机性。存储的数据在底层数组中并非按照数组索引顺序添加,而是根据数据的hash值
2.不可重复:保证添加的元素按照equals()判断时,不能返回true,即相同元素只能添加一个
二、添加数据过程(以HashSet为例)
向HashSet中添加元素a,首先调用元素a所在类的hashCode()方法,计算元素a的哈希值,此哈希值通过某种算法
算出元素在HashSet底层数组中的存放位置(即为索引位置),判断数组此位置是否已经有元素,如果没有,则存放成功
----->情况一
如果此位置上有其他元素b(或以链表形式存在的多个元素),则比较a与b的哈希值是否一致,如果哈希值不同,添加成功
----->情况二
如果相同,进而调用a的equals()方法:返回true,添加失败
返回false,添加成功
----->情况三
对于添加成功的情况一和三,此位置已经存在元素,则a与该元素将以链表方式存储
JDK7中:元素a放在数组中,指向原来的元素
JDK8中:原来的元素在数组中,指向元素a
HashSet底层:数组加链表
*/
@Test
public void test(){
Set set = new HashSet();
set.add(123);
set.add(234);
set.add(234);
set.add("AA");
set.add("CC");
set.add(new Person("Tom",22));
set.add(new Person("Tom",22));
set.add(256);
Iterator iterator = set.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
//LinkedHashSet使用
//LinkedHashSet作为HashSet,在添加数据同时,每个数据还维护了两个引用,记录此数据前一个数据和后一个数据
//优点:遍历效率高于HashSet
@Test
public void test1(){
Set set = new LinkedHashSet();
set.add(123);
set.add(234);
set.add(234);
set.add("AA");
set.add("CC");
set.add(new Person("Tom",22));
set.add(new Person("Tom",22));
set.add(256);
Iterator iterator = set.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
package com.www.java2;
import com.www.java.Person;
import org.junit.Test;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
/**
*
* @author www
* @creat 2022-{MONTH}-{DAY}
*/
public class TreeSetTest {
/*
1.向TreeSet中添加的数据,要求是相同类的对象
2.两种排序方式:自然排序(Comparable)VS自定义排序(Comparator)
3.自然排序中,比较两个对象是否相同:compareTo()返回0,不再是equals()
3.定制排序中,比较两个对象是否相同:compare()返回0,不再是equals()
*/
@Test
public void test(){
TreeSet set = new TreeSet();
//失败,不同类型
// set.add(123);
// set.add(456);
// set.add("AA");
// set.add(new Person("Tom",23));
//例子1
// set.add(1234);
// set.add(456);
// set.add(789);
// set.add(123);//输出结果按照从小到大顺序
//例子2
set.add(new Person("Tom",23));
set.add(new Person("Jim",21));
set.add(new Person("Jerry",22));
set.add(new Person("Lucia",23));
set.add(new Person("Marry",33));
Iterator iterator = set.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
@Test
public void test2(){
Comparator comparator = new Comparator(){
//按照年龄从小到大(如果有同龄不同名的可以再添加判断)
@Override
public int compare(Object o1, Object o2) {
if(o1.getClass() == Person.class && o2.getClass() == Person.class){
Person p1 = (Person)o1;
Person p2 = (Person)o2;
return Integer.compare(p1.getAge(),p2.getAge());
}else{
throw new RuntimeException("输入类型不匹配");
}
}
};
TreeSet set = new TreeSet(comparator);
set.add(new Person("Tom",23));
set.add(new Person("Jim",21));
set.add(new Person("Jerry",22));
set.add(new Person("Lucia",23));
set.add(new Person("Marry",33));
Iterator iterator = set.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
练习
package com.www.java;
/**
* @author www
* @creat 2022-{MONTH}-{DAY}
*/
public class MyDate {
private int year;
private int month;
private int day;
public MyDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
@Override
public String toString() {
return year + "-" + month + "-" + day;
}
}
package com.www.java;
/**
* @author www
* @creat 2022-{MONTH}-{DAY}
*/
public class Employee implements Comparable{
private String name;
private int age;
private MyDate birthday;
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;
}
public MyDate getBirthday() {
return birthday;
}
public void setBirthday(MyDate birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
", birthday=" + birthday +
'}';
}
public Employee(String name, int age, MyDate birthday) {
this.name = name;
this.age = age;
this.birthday = birthday;
}
//name排序
@Override
public int compareTo(Object o) {
if(o.getClass() == getClass()){
Employee e = (Employee) o;
return e.name.compareTo(name);
}else{
throw new RuntimeException("类型不匹配");
}
}
}
package com.www.java;
import org.junit.Test;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
/**
* @author www
* @creat 2022-{MONTH}-{DAY}
*/
public class TreeSetTest {
@Test
public void test(){
MyDate myDate = new MyDate(1995, 6, 30);
MyDate myDate1 = new MyDate(1995, 10, 30);
MyDate myDate2 = new MyDate(1996, 8, 9);
MyDate myDate3 = new MyDate(1994, 1, 25);
MyDate myDate4 = new MyDate(1993, 3, 7);
Employee employee = new Employee("张三", 27, myDate);
Employee employee1 = new Employee("李四", 27, myDate1);
Employee employee2 = new Employee("王五", 26, myDate2);
Employee employee3 = new Employee("赵六", 28, myDate3);
Employee employee4 = new Employee("钱三", 29, myDate4);
TreeSet set = new TreeSet();
set.add(employee);
set.add(employee1);
set.add(employee2);
set.add(employee3);
set.add(employee4);
Iterator iterator = set.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
Comparator com = new Comparator(){
@Override
public int compare(Object o1, Object o2) {
if(o1.getClass() == Employee.class && o2.getClass() == Employee.class){
Employee p1 = (Employee) o1;
Employee p2 = (Employee) o2;
// if(p1.getBirthday().getYear() < p2.getBirthday().getYear()){
// return -1;
// }else if(p1.getBirthday().getYear() == p2.getBirthday().getYear() && p1.getBirthday().getMonth() < p2.getBirthday().getMonth()){
// return -1;
// }else if (p1.getBirthday().getYear() == p2.getBirthday().getYear() && p1.getBirthday().getMonth() == p2.getBirthday().getMonth()
// && p1.getBirthday().getDay() < p2.getBirthday().getDay()){
// return -1;
// }else if(p1.getBirthday().getYear() == p2.getBirthday().getYear() && p1.getBirthday().getMonth() == p2.getBirthday().getMonth()
// && p1.getBirthday().getDay() == p2.getBirthday().getDay()){
// return 0;
// }else{
// return 1;
// }
MyDate date1 = p1.getBirthday();
MyDate date2 = p2.getBirthday();
int minYear = date1.getYear() - date2.getYear();
if(minYear != 0){
return minYear;
}
int minMonth = date1.getMonth() - date2.getMonth();
if(minMonth != 0){
return minMonth;
}
int minDay = date1.getDay() - date2.getDay();
if(minDay != 0){
return minDay;
}
return 0;
}else{
throw new RuntimeException("输入类型不匹配");
}
}
};
TreeSet set1 = new TreeSet(com);
set1.add(employee);
set1.add(employee1);
set1.add(employee2);
set1.add(employee3);
set1.add(employee4);
System.out.println("**********");
Iterator iterator1 = set1.iterator();
while(iterator1.hasNext()){
System.out.println(iterator1.next());
}
}
}