集合的概念
概念:对象的容器,定义了对多个对象进行操作的常用方法。可实现数组的功能。
和数组区别:
1.数组长度固定,集合长度不固定
2.数组可以存储基本类型和引用类型,集合只能存储引用类型
位置:java.util.*;
Collection体系接口
该体系结构的根接口,代表一组对象,称为“集合”。
List接口的特点:有下标、元素可重复
Set接口的特点:无下标、元素不能重复
Collection的使用
* 1.添加元素 * 2.删除元素 * 3.遍历元素 * 4.判断
Collection父接口
特点:代表一组任意类型的对象,无序,无下标
声明Collection集合:
Collection 集合名 = new ArrayList();
方法:
- boolean add(Object obj)//添加一个对象。
- boolean addAll(Collection c)//将一个集合中的所有对象添加到此集合中。
- void clear()//清空此集合中的所有对象。
- boolean contains(Object o)//检查此集合中是否包含o对象
- boolean equals(Object o)//比较此集合是否与指定对象相等。
- boolean isEmpty)l/判断此集合是否为空
- boolean remove(Object o)//在此集合中移除o对象
- int size()//返回此集合中的元素个数。
- Object[] toArray0)//将此集合转换成数组。
声明Iterator迭代器:
Iterator 对象名 = 集合名.iterator();
Iterator的方法有:
//hasNext();有没有下一个元素
//next();获取下一个元素
//remove();删除当前元素
使用方法:
Collection collection = new ArrayList();
//添加元素
collection.add("苹果");
collection.add("西瓜");
collection.add("榴莲");
System.out.println("元素个数:"+collection.size());
System.out.println(collection);
//删除元素
// collection.remove("榴莲");
// System.out.println("删除之后:"+collection.size());
// System.out.println(collection);
//清空
// collection.clear();
// System.out.println("清空之后:"+collection.size());
// System.out.println(collection);
//遍历元素[重点]
//3.1 使用增强for
System.out.println("----3.1使用增强for(也就是forEach)-----");
for (Object object: collection) {
System.out.println(object);
}
System.out.println("----------3.2使用迭代器---------");
//3.2使用迭代器(迭代器专门用来遍历集合)
//iterator是个接口
//hasNext();有没有下一个元素
//next();获取下一个元素
//remove();删除当前元素
Iterator iterator = collection.iterator();
while (iterator.hasNext()){
String s =(String) iterator.next();
System.out.println(s);
//在进行迭代器使用时不能使用collection删除方法
//collection.remove(s);
//应当使用 iterator.remove();进行元素删除
}
System.out.println("元素个数:"+collection.size());
System.out.println(collection);
//判断
//collection.contains("西瓜"):判断里边是否存在西瓜这个对象
//collection.isEmpty():判断集合是否为空
System.out.println(collection.contains("西瓜"));
System.out.println(collection.isEmpty());
遍历集合元素的方法:分两种
//第一种:(foreach循环)
for (Object object: collection) {
System.out.println(object);
}
//第二种:(迭代器)
//iterator是个接口
//hasNext();有没有下一个元素
//next();获取下一个元素
//remove();删除当前元素
Iterator iterator = collection.iterator();
while (iterator.hasNext()){
//强制类型转换,将对象转为字符串
String s =(String) iterator.next();
System.out.println(s);
}
//在进行迭代器使用时不能使用collection删除方法
collection.remove(s);//不能使用
//应当使用 iterator.remove();进行元素删除
iterator.remove();//正确
示例:(使用collection来保存学生信息)
//学生类(两个属性,构造方法,get和set方法,toString方法)
public class Student {
private String name;
private int age;
public Student() {
}
public Student(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 "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
//测试类
public class Demo02 {
public static void main(String[] args) {
//创建集合
Collection collection = new ArrayList();
//添加数据
Student s1 = new Student("xiaoRan",19);
Student s2 = new Student("RanLing",18);
Student s3 = new Student("LinRan",20);
collection.add(s1);
collection.add(s2);
collection.add(s3);
collection.add(s3);
System.out.println("元素个数"+collection.size());
System.out.println(collection.toString());
//删除
// 清空:collection.clear();
// System.out.println("删除之后"+collection.size());
// System.out.println(collection.toString());
//遍历
//增强foreach
for (Object c:collection) {
//强制类型转换
Student s = (Student) c;
System.out.println(s.toString());
}
//迭代器
Iterator iterator = collection.iterator();
while (iterator.hasNext()){
Student s = (Student) iterator.next();
System.out.println(s.toString());
}
//判断
System.out.println(collection.contains(s1));
}
}
List子接口
特点:有序,有下标,元素可以重复
方法:
声明List集合:
List 集合名 = new ArrayList();
方法:
1.void add(int index,Object o);//在index位置插入对象o
Boolean addAll(int index,Collection o);//将一个集合中的元素添加到此集合中的index位置
Object get(int index);//返回集合中指定位置的元素.
List SubList(int fromIndex,int toIndex)//返回fromIndex和toIndex之间的集合元素
声明ListIterator迭代器:
ListIterator 对象名 = 集合名.listIterator();
使用列表迭代器,和iterator的区别,ListIterator可以想前或向后遍历,添加,删除,修改元素,意思是List集合合有自己独有的迭代器
方法:
add("元素"); //将指定的元素插入列表
hasNext() ;//有没有下一个元素
hasPrevious() ;//有没有上一个元素(一般用于逆向遍历)
next() ;//获取下一个元素(前进光标位置)
nextIndex() ;//获取下个元素的下标
previous() ;//获取上一个元素(后退光标位置)
previousIndex() ;//获取上个元素的下标
remove("元素") ;//删除这个元素
set("元素") ;//添加元素
**注意**:
//前提是:不能湿数字类型数据
//List进行删除,也就是ist.remove("要删除的元素名或者下标!")
//remove是通过下标进行删除的,所以数字元素就不能直接remove("元素")进行删除了
删除方法:
list.remove((Object) 20);或者 list.remove(new Integer(20));都可以进行删除
示例:
public class Demo03 {
public static void main(String[] args) {
List list = new ArrayList();
//1.添加元素
list.add("苹果");
list.add("小米");
list.add(0,"华为");
System.out.println("元素个数:"+list.size());
System.out.println(list.toString());
//2.删除元素
//list.remove("苹果");
//list.remove(1);
//System.out.println("元素个数:"+list.size());
//System.out.println(list.toStr ing());
//3.遍历
//3.1使用for遍历
System.out.println("使用for遍历:");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
//3.2使用增强for
System.out.println("使用foreach遍历:");
for (Object l : list) {
System.out.println(l);
}
//3.3使用迭代器
System.out.println("使用迭代器:");
Iterator iterator = list.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
//3.4使用列表迭代器,和iterator的区别,ListIterator可以想前或向后遍历,添加,删除,修改元素
ListIterator listIterator = list.listIterator();
System.out.println("使用列表地带选择器从前往后:");
while (listIterator.hasNext()){
System.out.println(listIterator.nextIndex()+":"+listIterator.next());
}
//4.使用列表迭代器后往前(前面指针已经移向后边,所以在这里不用指针后移)
System.out.println("使用列表迭代器后往前");
while (listIterator.hasPrevious()){
System.out.println(listIterator.previousIndex()+":"+listIterator.previous());
}
//判断
System.out.println(list.contains("苹果"));
System.out.println(list.isEmpty());
//获取位置
System.out.println(list.indexOf("小米"));
}
}
List常见实现类
ArrayList:
源码分析:
默认容量:DEFAULT_CAPACITY = 10;//在添加元素之后默认容量为10
//注意:如果没有向集合中添加任何元素,容量为0
//每次扩容大小是原来的1.5倍
存放元素的数组:elementData
实际的元素数:size
添加元素:add();
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
if(elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA){
minCapacity = Math.max(DEFAULT_CAPACITY,minCapacity)
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
ArrayList的使用:
//学生类
public class Student {
private String name;
private int age;
public Student() {
}
public Student(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 "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
//判断是不是同一个对象
if (this==o){
return true;
}
//判断是否为空
if (o==null){
return false;
}
//判断是否是Student类型
if (o instanceof Student){
Student student = (Student) o;
//比较属性
if (this.name.equals(student.getName())&&this.age==(student.getAge())){
return true;
}
}
//5.不满足条件返回false
return false;
}
}
//测试类
public class Demo05 {
public static void main(String[] args) {
//创建ArrayList集合 size为0 容量为0
//每次扩容原来的1.5倍
ArrayList arrayList = new ArrayList();
//1.添加元素
Student s1 = new Student("小冉", 19);
Student s2 = new Student("林冉", 20);
Student s3 = new Student("XiaoRan", 18);
Student s4 = new Student("LinRan", 21);
arrayList.add(s1);
arrayList.add(s2);
arrayList.add(s3);
arrayList.add(s4);
System.out.println("元素个数:"+arrayList.size());
System.out.println(arrayList.toString());
//2.删除元素
arrayList.remove(new Student("林冉",20));
System.out.println("元素个数:"+arrayList.size());
System.out.println(arrayList.toString());
//3.遍历元素(重点)
//使用迭代器
System.out.println("使用迭代器:");
Iterator iterator = arrayList.iterator();
while (iterator.hasNext()){
Student student = (Student)iterator.next();
System.out.println(student.toString());
}
//使用列表迭代器
System.out.println("使用列表迭代器");
ListIterator listIterator = arrayList.listIterator();
while (listIterator.hasNext()){
System.out.println(listIterator.nextIndex()+":"+ listIterator.next());
}
//逆序
System.out.println("逆序输出");
while (listIterator.hasPrevious()) {
Student s = (Student)listIterator.previous();
System.out.println(s.toString());
}
//判断
System.out.println(arrayList.contains(new Student("XiaoRan",18)));
System.out.println(arrayList.isEmpty());
//查找
System.out.println(arrayList.indexOf(new Student("XiaoRan",18)));
}
}
Vector:
item:实时数据
next:下一个节点
prev:前一个节点
private void linkFirst(E e) {
final Node<E> f = first;
final Node<E> newNode = new Node<>(null, e, f);
first = newNode;
if (f == null)
last = newNode;
else
f.prev = newNode;
size++;
modCount++;
}
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
Vector的使用:
public class Demo01 {
public static void main(String[] args) {
//创建集合
Vector vector = new Vector();
//1.添加元素
vector.add("草莓");
vector.add("芒果");
vector.add("西瓜");
System.out.println("元素个数"+vector.size());
// 删除
// vector.remove("西瓜");
// vector.clear();
//元素遍历
//使用枚举器
Enumeration enumeration = vector.elements();
while (enumeration.hasMoreElements()) {
String o= (String) enumeration.nextElement();
System.out.println(o);
}
//判断
System.out.println(vector.contains("西瓜"));
System.out.println(vector.isEmpty());
//vector其他方法
//firstElement,lastElement,elementAt
}
}
LinkedList的使用:
//创建集合
LinkedList linkedList = new LinkedList();
//添加元素
Student s1 = new Student("小冉", 19);
Student s2 = new Student("林冉", 20);
Student s3 = new Student("XiaoRan", 18);
Student s4 = new Student("LinRan", 21);
linkedList.add(s1);
linkedList.add(s2);
linkedList.add(s3);
linkedList.add(s4);
System.out.println("元素个数:"+linkedList.size());
System.out.println(linkedList.toString());
//删除
// linkedList.remove(s1);
// System.out.println("删除之后:"+linkedList.size());
// System.out.println(linkedList.toString());
// linkedList.clear();
// System.out.println("清空之后:"+linkedList.size());
// System.out.println(linkedList.toString());
//遍历
System.out.println("for遍历:");
for (int i = 0; i < linkedList.size(); i++) {
System.out.println(linkedList.get(i));
}
//foreach
System.out.println("foreach遍历:");
for (Object link:linkedList) {
Student student = (Student) link;
System.out.println(student);
}
//迭代器
System.out.println("迭代器:");
Iterator iterator = linkedList.iterator();
while (iterator.hasNext()) {
Student student = (Student) iterator.next();
System.out.println(student);
}
//列表迭代器
System.out.println("列表迭代器:");
ListIterator listIterator = linkedList.listIterator();
while (listIterator.hasNext()) {
Student student = (Student) listIterator.next();
System.out.println(student);
}
//判断
System.out.println(linkedList.contains(s1));
System.out.println(linkedList.isEmpty());
//获取
System.out.println(linkedList.indexOf(s1));
ArrayList和LinkedList的区别
ArrayList:必须开辟连续空间,查询快增删慢.
LinkedList:无需开辟连续空间,查询慢,增删快.
泛型
Integer关键字:
它是一个类,是 int 基本数据类型的封装类。
Integer 是类,默认值为null,int是基本数据类型,默认值为0;
Integer 表示的是对象,用一个引用指向这个对象,而int是基本数据类型,直接存储数值。
本质是参数化类型,把类型作为参数传递
常见形式有:泛型类,泛型接口,泛型方法
语法:
<T,....>T成为类型占位符,表示一种引用类型
好处:
1.提高代码的重用性
2.防止类型转换异常,提高代码的安全性
泛型类:
语法:
类名<T,E,K> //T是类型占位符,表示一种引用类型,如果编写多个使用,号隔开
public class MyGeneric <T>{
//使用泛型T
//T可以创建变量,但是不可以去new对象(也就是不能实例化)
//创建变量
T t;
//泛型作为方法的参数
public void show(T t){
System.out.println(t);
}
//泛型作为方法的返回值
public T getT(){
return t;
}
}
//测试类
public class TestMyGeneric {
public static void main(String[] args) {
/*
* 注意:
* 泛型类只能使用引用类型
* 不同的泛型类不能相互赋值
* */
MyGeneric<String> myGeneric=new MyGeneric<String>();
myGeneric.t = "小冉";
myGeneric.show("依旧是小冉");
String string = myGeneric.getT();
System.out.println(string);
MyGeneric<Integer> myGeneric1 = new MyGeneric<Integer>();
myGeneric1.t = 100;
myGeneric1.show(200);
Integer integer = myGeneric1.getT();
System.out.println(integer);
//不同的泛型类不能相互赋值
//同类型可以
MyGeneric<String> myGeneric3=myGeneric;
//不同类型不行
//MyGeneric<String> myGeneric4=myGeneric1;
}
}
泛型接口
* 语法:接口名<T>
*
* 注意不能创建泛型静态常量
//接口
public interface MyInterface <T>{
String name = "小冉";
T sever(T t);
}
//实现接口类:第一种
//直接给到泛型类型
public class MyInterfaceImpl implements MyInterface<String>{
@Override
public String sever(String T) {
System.out.println(T);
return T;
}
}
//实现接口类:第二种
//系统识别泛型类型,实例化传参的时候给定
public class MyInterfaceImpl2<T> implements MyInterface<T>{
@Override
public T sever(T t) {
System.out.println(t);
return t;
}
}
//测试类
public class MyInterfaceTest {
public static void main(String[] args) {
MyInterfaceImpl impl = new MyInterfaceImpl();
impl.sever("小冉");
MyInterfaceImpl2<Integer> ipml2 = new MyInterfaceImpl2<>();
impl.sever("name");
}
}
泛型方法
* 语法:
* <T> 方法返回值 方法名
//方法类
public class MyGenericMethod {
//无返回值类型
// public <T> void show(T t){
// System.out.println("泛型方法:"+t);
// }
//有返回值类型
public <T> T show(T t){
System.out.println("泛型方法:"+t);
return t;
}
}
//测试类
public class Test {
public static void main(String[] args) {
//泛型方法
MyGenericMethod method = new MyGenericMethod();
method.show("依旧小冉");
method.show(1000);
method.show(3.1415926);
}
}
泛型集合
//声明泛型集合 类型为String
ArrayList<String> arrayList = new ArrayList<String>();
//添加元素
arrayList.add("xiaoRan");
arrayList.add("小冉");
//因为声明集合的时候给定了String的类型,所以不能添加数字,添加数字会报错
// arrayList.add(19);
// arrayList.add(20);
//foreach遍历
for (String s : arrayList) {
System.out.println(s);
}
//声明泛型数组,类型为Student类型
ArrayList<Student> arrayList1 = new ArrayList<Student>();
Student s1 = new Student("xiaoRan",19);
Student s2 = new Student("RanLing",18);
Student s3 = new Student("LinRan",20);
//添加元素
arrayList1.add(s1);
arrayList1.add(s2);
arrayList1.add(s3);
//因为类型为Student类型,所以不能添加字符
// arrayList1.add("sss");
//迭代器
Iterator<Student> iterator = arrayList1.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
Set集合
Set子接口
特点:无序,无下标,元素不可重复
方法:全部继承自Collection中的方法
set接口的使用:
public class Demo01 {
public static void main(String[] args) {
//创建集合
//HashSet是Set的实现类
Set<String> set = new HashSet<>();
//1.添加数据
set.add("小米");
set.add("苹果");
set.add("华为");
//重复的添加不进去
// set.add("华为");
System.out.println(set.size());
System.out.println(set.toString());
//2.删除
set.remove("小米");
System.out.println(set.size());
System.out.println(set.toString());
//清空
set.clear();
System.out.println(set.size());
System.out.println(set.toString());
//遍历
//使用增强for
//因为没有下标,所以不能使用for循环
System.out.println("foreach遍历");
for (Object object:set) {
System.out.println(object);
}
System.out.println("迭代器遍历");
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
//判断
System.out.println(set.contains("华为"));
System.out.println(set.isEmpty());
}
}
Set实现类
HashSet[重点]:
1.基于HashCode实现元素不重复
2.当存入元素的哈希码相同时,会调用equals进行确认,如果为true,则拒绝后者存入
TreeSet:
基于排列顺序实现元素不重复
HashSet集合的使用
存储结构:哈希表(数组+链表+红黑树)
HashSet存储数据不允许出现重复的数据
* 存储过程(重复的依据 ):
* 1.根据hasCode:计算保存的位置如果此位置为空,则直接保存,如果不为空则执行第二部
* 2.在执行equals方法,如果equals方法为true,则认为是重复否则,形成链表
//新建集合
HashSet<String> hashSet = new HashSet<String>();
//1.添加元素
hashSet.add("小冉");
hashSet.add("林冉");
hashSet.add("xiaoRan");
hashSet.add("linRan");
//hashSet.add("linRan"); 不允许出现重复的
System.out.println("元素个数:"+hashSet.size());
System.out.println(hashSet.toString());
//2.删除元素
hashSet.remove("林冉");
System.out.println(hashSet.toString());
//遍历操作
//增强for
for (Object o: hashSet){
System.out.println(o);
}
//使用迭代器
System.out.println("使用迭代器:");
Iterator<String> iterator = hashSet.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
System.out.println(hashSet.contains("linRan"));
System.out.println(hashSet.isEmpty());
HashSet添加对象的使用(重写了equals之后添加不进去…)
public class Demo03 {
public static void main(String[] args) {
HashSet<Person> person = new HashSet<>();
//添加数据
Person person1 = new Person("小冉", 19);
Person person2 = new Person("林冉", 22);
Person person3 = new Person("xiaoRan", 20);
person.add(person1);
person.add(person2);
person.add(person3);
//重写equals之后添加不进去
person.add(new Person("xiaoRan",20));
//person.add(person3);重复的不可以重复添加
System.out.println("元素个数:"+person.size());
System.out.println(person.toString());
//删除操作
//person.remove(new Person("xiaoRan",20));
System.out.println("删除之后:"+person.size());
System.out.println(person.toString());
//遍历
System.out.println("遍历");
//增强for
System.out.println("增强for:");
for (Person p:person) {
System.out.println(p.toString());
}
System.out.println("迭代器");
Iterator<Person> iterator = person.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
System.out.println(person.contains(person1));
System.out.println(person.isEmpty());
}
}
//Person类
public class Person {
private String name;
private 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) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
TreeSet的使用
存储结构:
红黑苏
//测试类
public class Demo04 {
public static void main(String[] args) {
//创建集合
TreeSet<String> treeSet = new TreeSet<>();
treeSet.add("xyz");
//treeSet.add("xyz"); 元素重复,不能添加
treeSet.add("abc");
treeSet.add("hello");
System.out.println("元素个数:"+treeSet.size());
System.out.println(treeSet.toString());
//删除
// treeSet.remove("xyz");
// System.out.println("删除之后:"+treeSet.size());
// System.out.println(treeSet.toString());
//遍历
//foreach
for (String string:treeSet) {
System.out.println(string.toString());
}
System.out.println("=========================");
//迭代器
Iterator<String> iterator = treeSet.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
System.out.println(treeSet.isEmpty());
System.out.println(treeSet.contains("abc"));
}
}
//Person类
public class Person{
private String name;
private 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 +
'}';
}
}
使用TreeSet保存数据
用compareTo重写比较规则
一般都在对象类里边重写(之前会写在测试类里边,但是现在尽量都去写在对象类中)
第一步:对象类继承Comparable<对象类名>
例如:
public class Person implements Comparable<Person>
第二部:去重写compareTo方法,如果方法的返回值为0的话,则认为是重复元素
重写compareTo
例如:
public int compareTo(Person o) {
//先按姓名比 如果姓名相同的话就比较年龄,如果年龄相同就为重复
int n1 = this.getName().compareTo(o.getName());
int n2 = this.getAge()-o.getAge();
return n1==0?n2:n1;
}
要求:元素必须实现Comparable接口,compareTo()方法的返回值为0,认为是重复元素
public class Demo05 {
public static void main(String[] args) {
//创建集合
TreeSet<Person> person= new TreeSet<>();
Person person1 = new Person("小冉", 19);
Person person2 = new Person("林冉", 22);
Person person3 = new Person("xiaoRan", 20);
Person person4 = new Person("xiaoRan", 25);
person.add(person1);
person.add(person2);
person.add(person3);
person.add(person4);
System.out.println("元素个数:"+person.size());
System.out.println(person.toString());
//删除
// person.remove(person1);
// System.out.println("删除之后:"+person.size());
// System.out.println(person.toString());
//遍历
for (Person p : person) {
System.out.println(p);
}
//迭代器
Iterator<Person> iterator = person.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
//判断
System.out.println(person.contains(person1));
System.out.println(person.isEmpty());
}
}
//Person类
public class Person implements Comparable<Person>{
private String name;
private 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) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
//先按姓名比,然后再按年龄比
@Override
public int compareTo(Person o) {
int n1 = this.getName().compareTo(o.getName());
int n2 = this.getAge()-o.getAge();
return n1==0?n2:n1;
}
}
Map接口的使用
HashMap的使用(存储String的数据)
* Map接口的使用
* 特点:
* 1.存储键值对
* 2.键不能重复,值可以重复
* 3.无序
方法:
V put(K key,V value)//讲对象存入到集合中,关联关键值.Key重复则覆盖
Object get(Object key)//根据键获取对应的值
Set<K> keySet()//返回所有的key
Collection<V> values()//返回包含所有值的Collection集合
Set<Map.Entry<K,V>>//键值匹配的Set集合
public class Demo01 {
public static void main(String[] args) {
//创建Map集合
Map<String, String> map = new HashMap<>();
//1添加元素
map.put("cn","中国");
//添加重复的键值,后面的值会把前面的值给覆盖掉
map.put("cn","China");
map.put("uk","英国");
map.put("usa","美国");
System.out.println("元素个数:"+map.size());
System.out.println(map.toString());
//2删除
// map.remove("usa");
// System.out.println("删除之后:"+map.size());
// System.out.println(map.toString());
//3.遍历
//3.1使用keySet();
System.out.println("----------keySet---------- ");
Set<String> set = map.keySet();
for (String key : set) {
System.out.println(key+":"+map.get(key));
}
//3.2使用entrySet();方法
System.out.println("----------entrySet---------");
Set<Map.Entry<String, String>> entries = map.entrySet();
for (Map.Entry<String, String> entry : entries) {
System.out.println(entry.getKey() + ":"+entry.getValue());
}
//4.判断
System.out.println(map.containsKey("cn"));
System.out.println(map.containsValue("泰国"));
}
}
HashMap的使用(存储对象的使用)
public class Demo02 {
public static void main(String[] args) {
//创建集合
HashMap<Student, String> student = new HashMap<>();
//添加元素
Student s1 = new Student("小冉", 100);
Student s2 = new Student("冉玲", 101);
Student s3 = new Student("林冉", 102);
student.put(s1,"上海");
student.put(s2,"北京");
student.put(s3,"成都");
//没有加进去
//student.put(s3,"南京");
student.put(new Student("小冉",100),"上海");
System.out.println("元素个数:"+student.size());
System.out.println(student.toString());
//2.删除
// student.remove(s1);
// System.out.println("删除之后:"+student.size());
//3.遍历
//3.1使用keySet();
System.out.println("===========使用keySet==============");
for (Student key: student.keySet()) {
System.out.println(key.toString()+"====>"+student.get(key));
}
System.out.println("===========使用entrySet============");
//3.2使用entrySet();
for (Map.Entry<Student, String> entry:student.entrySet()) {
System.out.println(entry.getKey() + ":"+entry.getValue());
}
//4.判断
System.out.println(student.containsKey(new Student("小冉",100)));
System.out.println(student.containsValue("杭州"));
}
}
//Student类
public class Student implements Comparable<Student>{
private String name;
private int stuNo;
public Student() {
}
public Student(String name, int stuNo) {
this.name = name;
this.stuNo = stuNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStuNo() {
return stuNo;
}
public void setStuNo(int stuNo) {
this.stuNo = stuNo;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", stuNo=" + stuNo +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return stuNo == student.stuNo && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, stuNo);
}
@Override
public int compareTo(Student o) {
int n2 = this.stuNo-o.stuNo;
return n2;
}
}
Collections实现类
public class Demo04 {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(20);
list.add(5);
list.add(12);
list.add(30);
list.add(6);
//sort排序
System.out.println("排序之前:"+list);
Collections.sort(list);
System.out.println("排序之后:"+list);
//binarySearch二分查找
//找到了是正数,找不到就是负数
int i = Collections.binarySearch(list, 13);
int n = Collections.binarySearch(list, 12);
System.out.println(i+":"+n);
//copy 复制
List<Integer> dest = new ArrayList<>();
for (int j = 0; j < list.size(); j++) {
dest.add(0);
}
Collections.copy(dest,list);
System.out.println(dest);
//reverse反转
Collections.reverse(list);
System.out.println("反转之后"+list);
//shuffle打乱
Collections.shuffle(list);
System.out.println("打乱之后"+list);
//补充:list转成数组
System.out.println("list转成数组:");
Integer[] arr = list.toArray(new Integer[0]);
System.out.println(arr.length);
System.out.println(Arrays.toString(arr));
//数组转成集合
System.out.println("数组转成集合");
String[] names = {"张三","李四","王五"};
//集合是一个受限集合,不能添加和删除
List<String> strings = Arrays.asList(names);
System.out.println(strings);
//把基本数据类型转成集合时,需要修改为包装类型
Integer[] nums = {100,200,300,400,500};
List<Integer> integers = Arrays.asList(nums);
System.out.println(integers);
}
}