集合的概念
集合是对象的容器,定义了对多个对象进行操作的常用方法,可以实现数组的功能
与数组的区别
- 数组长度固定,集合长度不固定
- 数组可以存储基本类型和引用类型,集合只能存储引用类型
- 集合位置:java.util.*
Collection体系集合
collection父接口
特点
代表一组任意类型的对象,无序、无下标,不能重复
使用collection接口时不能直接new collection接口而是要借助它下面List,set,Map的实现类来调用
Collection c=new ArrayList();
方法
- boolean add(Object obj) :添加一个对象
Collection c=new ArrayList();
c.add(100);
c.add("测试");
System.out.println(c);
- boolean addAll(Collection c) :将一个集合中的所有对象添加到此集合
Collection c=new ArrayList();
c.add("测试");
c.add(100);
Collection c2=new ArrayList();
c2.addAll(c);
System.out.println(c2);
- void clear():清空此集合中的所有对象
Collection c=new ArrayList();
c.add("测试");
c.add(100);
c.clear();
boolean d=c.isEmpty();
System.out.println(d); //输出true,集合类元素已经被清空
- boolean contains(Object o):检查此集合是否包含o对象
Collection c=new ArrayList();
c.add("测试");
c.add(100);
boolean a=c.contains(100);
boolean b=c.contains(200);
System.out.println(a); //true
System.out.println(b); //false
- boolean equals(Object o):比较此集合是否与指定对象相等
Collection c=new ArrayList();
c.add("测试");
c.add(100);
Collection c1=new ArrayList();
c1.add("测试");
c1.add(100);
Collection c2=new ArrayList();
c2.add(299);
boolean a=c.equals(c1);
boolean b=c.equals(c2);
System.out.println(a);
System.out.println(b);
- boolean isEmpty():判断此集合是否为空
Collection c=new ArrayList();
boolean a=c.isEmpty();
System.out.println(a);
- int size():返回此集合中的元素个数
Collection c=new ArrayList();
int s=c.size();
System.out.println(s);
- Object[] toArray():将此集合转换成数组
Collection c=new ArrayList();
c.add("测试");
c.add(299);
Object s[]=c.toArray();
for(int i=0;i<s.length;i++){
System.out.println(s[i]);}
- boolean remove(Object obj):删除集合中的某个元素
Collection c=new ArrayList();
c.add("测试");
c.add(200);
c.add(true);
c.remove("测试");
System.out.println(c);
- 集合遍历
使用增加for
Collection c=new ArrayList();
c.add("测试");
c.add(200);
c.add(true);
for(Object obj:c){
System.out.println(obj);}
迭代器 Iterator :一次遍历集合中的元素
Collection c=new ArrayList();
c.add("测试");
c.add(200);
c.add(true);
Iterator it=c.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
在进行Iterator迭代器时不允许使用Collection的remove()进行删除,只能使用迭代器自带的删除方法remove();
List子接口
特点
有序,有下标,元素可以重复
List list=new ArrayList<>();
方法
注意:Collection的方法List都可以使用
- void add(int index,Object o):在index位置插入对象o
List list=new ArrayList<>();
list.add("测试");
list.add(11);
list.add(1,299);
System.out.println(list);
- boolean addAll(int index,Collection c):将一个集合中的元素添加到此集合中的index位置
List list=new ArrayList<>();
list.add("测试");
list.add(200);
list.add(33);
List list1=new ArrayList<>();
list1.add("我是新添加的元素");
list.addAll(1,list1);
System.out.println(list);
- Object get(int index):返回集合中指定位置的元素
List list=new ArrayList<>();
list.add("测试");
list.add(200);
list.add(33);
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));}
- List subList(int fromIndex,int toIndex):返回FromIndex和toIndex之间的元素的子集合
注意:包含fromIndex位置上的元素,不包含toIndex位置上的元素
List list=new ArrayList<>();
list.add("测试");
list.add(200);
list.add(33);
System.out.println(list.subList(1,3));
- boolean remove(int index):删除index下标的元素
List list=new ArrayList<>();
list.add("测试");
list.add(200);
list.add(33);
list.remove(1);
System.out.println(list);
- boolean clear():清空集合中的元素
List list=new ArrayList<>();
list.add("测试");
list.add(200);
list.add(33);
list.clear();
System.out.println(list.isEmpty());
- 集合遍历
使用for来进行遍历
List list=new ArrayList<>();
list.add("测试");
list.add(200);
list.add(33);
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));}
使用增强for
for(Object obj:list){
System.out.println(obj);}
使用迭代器(Iterator)来进行遍历
Iterator it=list.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
使用列表迭代器(listIterator)来进行遍历
和Iterator的区别:ListIterator可以向前和向后遍历,也可以添加删除修改元素
ListIterator lit=list.listIterator();
while(lit.hasNext()){
System.out.println(lit.nextIndex()+":"+lit.next());
}
- boolean contains(Object obj):判断该元素是否存在
List list=ArrayList<>();
list.add(199);
boolean a=list.contains("测试");
System.out.println(a);
- Boolean isEmpty():判断集合是否为空
List list=ArrayList<>();
list.add(199);
boolean a=list.isEmpty("测试");
System.out.println(a);
- int indexOf(Object obj):获取元素所在位置
List list=ArrayList<>();
list.add(199);
int a=list.indexOf(199);
System.out.println(a);
List的子类
ArrayList【重点】
特点
数组结构实现,查询快,增删慢
使用
存储结构:数组,查找遍历速度快,增删速度慢
ArrayList list=new ArrayList<>();
Student student=new Student("测试",2);
//添加
list.add("测试");
list.add(200);
list.add(true);
list.add(200);
String a="我可以删掉吗";
list.add(a);
list.add(student);
System.out.println(list);
//删除
list.remove("测试");
System.out.println(list);
list.remove(new Student("测试", 2));
System.out.println(list.size());
//如果添加自定义的类型到集合中时,使用remove进行new 的删除是无法删除的,此处涉及到堆栈的原理,若不懂可以重看一遍堆栈,但若想强制删除需要在其自定义类中重写equals()方法,具体写法请看最下方代码
//遍历
//使用迭代器
Iterator it=list.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
//使用列表迭代器
ListIterator lit=list.listIterator();
while(lit.hasNext()){
System.out.println(it.next());
}
//判断
System.out.println(list.contains("测试");
System.out.println(list.isEmpty());
//查找
System.out.println(list.indexOf("测试");
重写equals()方法
@Override
public boolean equals(Object obj) {
//判断是否是不是同一个对象
if(this==obj) {
return true;
}
//判断是否为空
if(obj==null) {
return false;
}
//判断是否是Student(自定义)类型
if (obj instanceof Student) {
Student student=(Student)obj;
//比较属性
if (this.nameString.equals(student.getNameString())&&this.age==student.getAge()){
return true;
}
}
//不满足返回false;
return false;
}
源码分析
- DEFAULT_CAPACITY = 10:默认容量大小
- 注意:如果没有向集合中添加任何元素时,容量为0,当添加元素后,容量则变为10,
- 每次扩容大小为原来的1.5倍
- elementData:存放元素
- size:实际的元素个数
- add():添加元素
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
//将容量变为10并返回
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, 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);
}
Vector
特点
数组结构实现,查询快,增删慢
JDK1.0版本,运行效率慢,线程安全
Vector集合的使用代码
Vector vector=new Vector<>();
//添加元素
vector.add("java");
vector.add("python");
vector.add("Vue");
System.out.println(vector);
//删除
vector.remove("java");
vector.remove(0);
//清空
vector.clear();
vector.add("java");
vector.add("python");
vector.add("Vue");
//遍历
//使用枚举器
Enumeration en=vector.elements();
while(en.hasMoreElements()){
String o=(String)en.nextElement();
System.out.println(o);
}
//判断
System.out.println(vector.contains("Python"));
System.out.println(vector.isEmpty());
//vector的其他方法
//firstElement(),lastElement(),elementAt()
LinkedList
特点
链表结构实现,增删快,查询慢
集合使用(双向链表)
LinkedList list=new LinkedList<>();
Student s1=new Student("张三",22);
Student s2=new Student("李华",23);
Student s3=new Student("王五",24);
//添加元素
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s2);
System.out.println(list.toString());
//删除
list.remove(s1);
System.out.println(list.toString());
list.remove(new Student("李华",23);
System.out.println(list.size());
//遍历
//for遍历
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));}
//增强for
for(Object ojb:list){
Student student=(Student)ojb;
System.out.println(student.toString());
}
//使用迭代器
Iterator it=list.iterator();
while(it.hasNext()){
Student s=(Student)it.next();
System.out.println(s.toString());
}
//使用列表迭代器
ListIterator lit=list.listIterator();
while(lit.hasNext(){
Student s=(Student)lit.next();
System.out.println(s.toString());
}
set
set的特点
- set接口时无序的
- set接口的数据不允许重复
- set接口中的数据不可以通过下标访问
- 查找慢,插入删除快
- 使用equals()和hashCode去重
set的实现类
set是一个接口,因此在使用它时,只能调用它的实现类来实现,其实现类有:hashSet,treeSet,LikedHashSet
set接口的方法
set接口没有特有的方法,它的方法都继承与Collection
set接口实现的简单例子
public class example{
public static void main(String args[]){
Set<String> set=new HashSet<String>();
//增加
set.add("苹果");
set.add("华为");
set.add("vivo");
set.add("华为");
System.out.println(set.size());
System.out.println(set.toString());
//删除
set.remove("苹果");
System.out.println(set.size());
System.out.println(set.toString());
//遍历 因此set集合没有下标,因此只能用两种方法进行遍历
//方法一、增加for循环
for(String string:set){
System.out.println(string);
}
//方法二、迭代器Iterator
Iterator<String> it=set.iterator();
while(it.hasNext){
System.out.println(it.next());
}
//判断
//判断该元素是否在集合中存在
System.out.println(set.contains("苹果"));
//判断该集合是否为空
System.out.println(set.isEmpty());
}
}
HashSet
HashSet的特点
- 基于HashCode计算元素存放位置
- 当存入元素的哈希码相同时,会调用equals()来进行确认,如果结果为true,则后者拒绝存入来保证HashSet中没有重复元素
例子说明
public class Student {
String nameString;
int age;
public Student(String nameString,int age) {
this.nameString=nameString;
this.age=age;
}
public void setAge(int age) {
this.age = age;
}public void setNameString(String nameString) {
this.nameString = nameString;
}
public int getAge() {
return age;
}
public String getNameString() {
return nameString;
}
@Override
public String toString() {
return "Student [nameString=" + nameString + ", age=" + age + "]";
}
}
public class example {
public static void main(String args[]){
Set<Student> hasSet=new HashSet<Student>();
Student s1=new Student("李明", 22);
Student s2=new Student("王华", 23);
Student s3=new Student("王五", 25);
hasSet.add(s1);
hasSet.add(s2);
hasSet.add(s3);
hasSet.add(s1);
System.out.println(hasSet.size());
System.out.println(hasSet.toString());
System.out.println("---------------------------");
hasSet.add(new Student("李明",22));
System.out.println(hasSet.size());
System.out.println(hasSet.toString());
hasSet.remove(s1);
System.out.println(hasSet.size());
System.out.println(hasSet.toString());
hasSet.remove(new Student("李明",22));
}
}
为何“李明”,22此数据明明重复但是依旧可以新增进去?为何有李明此条数据但是仍旧无法删除?
此处涉及到的原理是堆栈
改进
在Student类中重写hasCode和equals来进行判断是否相同,相同则返回true阻止新增,不同则返回false,进行新增
public class Student {
String nameString;
int age;
public Student(String nameString,int age) {
this.nameString=nameString;
this.age=age;
}
public void setAge(int age) {
this.age = age;
}public void setNameString(String nameString) {
this.nameString = nameString;
}
public int getAge() {
return age;
}
public String getNameString() {
return nameString;
}
@Override
public String toString() {
return "Student [nameString=" + nameString + ", age=" + age + "]";
}
@Override
public int hashCode() {
int n1=this.nameString.hashCode();
int n2=this.age;
return n1+n2;
}
@Override
public boolean equals(Object obj) {
if (this==obj) {
return true;
}
if (obj==null) {
return false;
}
if (obj instanceof Student) {
Student student=(Student) obj;
if (this.nameString.equals(student.getNameString())&&this.age==student.age) {
return true;
}
}
return false;
}
}
TreeSet
TreeSet的特点
- 基于排列顺序实现元素不重复
- 实现了SortedSet接口,对集合元素自动排序
- 元素对象的类型必须实现Comparable接口,指定排序规则
- 通过CompareTo方法确定是否为重复元素
TreeSet集合元素不重复示意图
简单例子
public class example{
public static void main(String args[]){
TreeSet<String> treeSet=new TreeSet<String>();
treeSet.add("xyz");
treeSet.add("abc");
treeSet.add("ABC");
treeSet.add("xyz");
System.out.println(treeSet.size());
System.out.println(treeSet.toString());
System.out.println("---------------分隔线-------------");
treeSet.remove("xyz");
System.out.println(treeSet.size());
System.out.println(treeSet.toString());
// 遍历 增强for
for (String list:treeSet) {
System.out.println(list);
}
// 遍历 迭代器
Iterator<String> it=treeSet.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
// 判断
System.out.println(treeSet.contains("abc"));
System.out.println(treeSet.isEmpty());
}
}
复杂例子
报错例子
public class Student {
String nameString;
int age;
public Student(String nameString,int age) {
this.nameString=nameString;
this.age=age;
}
public void setAge(int age) {
this.age = age;
}public void setNameString(String nameString) {
this.nameString = nameString;
}
public int getAge() {
return age;
}
public String getNameString() {
return nameString;
}
@Override
public String toString() {
return "Student [nameString=" + nameString + ", age=" + age + "]";
}
}
public class cs{
public static void main(String args[]){
TreeSet<Student> treeSet=new TreeSet<Student>();
Student s1=new Student("易烊千玺", 22);
Student s2=new Student("朱一龙", 24);
Student s3=new Student("迪丽热巴", 27);
treeSet.add(s1);
System.out.println(treeSet.toString());
}
}
运行截图如下
解决方法(在Student类继承Comparable接口,重写compareTo方法,若compareTo的返回值为0则认为是重复元素,则不进行添加)
public class Student implements Comparable<Student> {
String nameString;
int age;
public Student(String nameString,int age) {
this.nameString=nameString;
this.age=age;
}
public void setAge(int age) {
this.age = age;
}public void setNameString(String nameString) {
this.nameString = nameString;
}
public int getAge() {
return age;
}
public String getNameString() {
return nameString;
}
@Override
public String toString() {
return "Student [nameString=" + nameString + ", age=" + age + "]";
}
//先按姓名比再按年龄比
@Override
public int compareTo(Student o) {
// TODO Auto-generated method stub
int n1=this.nameString.compareTo(o.nameString);
int n2=this.age-o.age;
return n1==0?n2:n1;
}
}
public class cs{
public static void main(String args[]){
TreeSet<Student> treeSet=new TreeSet<Student>();
Student s1=new Student("易烊千玺", 22);
Student s2=new Student("朱一龙", 24);
Student s3=new Student("迪丽热巴", 27);
Student s4=new Student("迪丽热巴", 26);
treeSet.add(s1);
treeSet.add(s2);
treeSet.add(s3);
treeSet.add(s1);
treeSet.add(s4);
System.out.println(treeSet.toString());
treeSet.remove(s1);
treeSet.remove(new Student("迪丽热巴", 27));
System.out.println(treeSet.toString()); //此时remove(new Student("迪丽热巴", 27))可以删除,因为比较的是Student里面的元素
}
}
Comparator接口的使用
public class Student{
String nameString;
int age;
public Student(String nameString,int age) {
this.nameString=nameString;
this.age=age;
}
public void setAge(int age) {
this.age = age;
}public void setNameString(String nameString) {
this.nameString = nameString;
}
public int getAge() {
return age;
}
public String getNameString() {
return nameString;
}
@Override
public String toString() {
return "Student [nameString=" + nameString + ", age=" + age + "]";
}
}
public class cs{
public static void main(String args[]){
TreeSet<Student> treeSet=new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
// 先比较姓名再比较年龄
int n1=o1.getNameString().compareTo(o2.getNameString());
int n2=o1.getAge()-o2.getAge();
return n1==0?n2:n1;
}
});
Student s1=new Student("易烊千玺", 22);
Student s2=new Student("朱一龙", 24);
Student s3=new Student("迪丽热巴", 27);
Student s4=new Student("迪丽热巴", 26);
treeSet.add(s1);
treeSet.add(s2);
treeSet.add(s3);
treeSet.add(s1);
treeSet.add(s4);
System.out.println(treeSet.toString());
treeSet.remove(s1);
treeSet.remove(new Student("迪丽热巴", 27));
System.out.println(treeSet.toString());
}
}
案例
通过长度对字符串进行排序,如果长度相同则按住原来规则进行排序
public class cs{
public static void main(String args[]){
TreeSet<String> treeSet=new TreeSet<String>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int n1=o1.length()-o2.length();
int n2=o1.compareTo(o2);
return n1==0?n2:n1;
}
});
treeSet.add("Hello");
treeSet.add("hhhhhhhhhhhhhh");
treeSet.add("bsbsbbsb");
treeSet.add("Words");
System.out.println(treeSet.toString());
}
}
Map集合
特点
存储一对数据,无序、无下标、键不可重复,值可重复
方法
- V put(K key,V value):将对象存入到集合中,关联键值,key重复着覆盖原值
- Object get(Object key):根据键获取对应的值
- Set:返回所有key
- Collection values():返回包含所有值的Collection集合
- Set<Map.Entry<K,V>>:键值匹配的Set集合
遍历的实现
Map集合的基本操作代码实现
Map<String, String> map=new HashMap<String, String>();
//新增
map.put("cn", "中国");
map.put("uk", "英国");
map.put("usa", "美国");
map.put("cn", "我是第二次添加进行来的中国");
System.out.println(map.toString());//打印的是cn的value值是最后一次的value值,因为map中key值不能重复,因此第一次和最后一次的key一样时,最后一次的key值就会覆盖前一次的key值
//删除
map.remove("cn");
System.out.println(map.toString());
//遍历
//1、entrySet()
Set<Map.Entry<String, String>> set=map.entrySet();
for (Map.Entry<String, String> entry:set) {
System.out.println(entry.getKey()+"------"+entry.getValue());
}
//2、KeySet
Set<String> set2=map.keySet();
for (String sets : set2) {
System.out.println(sets+"-------"+map.get(sets));
}
//判断有没有key或有没有value
System.out.println(map.containsKey("usa"));
System.out.println(map.containsValue("我是第二次添加进行来的中国"));
实现类:HashMap(重点)
特点
存储结构
哈希表(数组+链表+红黑树)
代码实现
Map<Student,String> map=new HashMap<Student, String>();
Student s1=new Student("小明","123");
Student s2=new Student("小华","234");
Student s3=new Student("小花","456");
map.put(s1, "重庆");
map.put(s2, "上海");
map.put(s3, "湖南");
map.put(new Student("小明","123"), "重庆");
System.out.println(map.size());
System.out.println(map.toString());
思考:输出为四个元素,但是Map说了key值不能重复为什么第四个元素明明重复但是依旧添加进去了?
此处涉及到堆栈原理
解决方法
package maps;
public class Student {
private String name;
private String stuNo;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStuNo() {
return stuNo;
}
public void setStuNo(String stuNo) {
this.stuNo = stuNo;
}
public Student() {
// TODO Auto-generated constructor stub
}
public Student(String name,String stuNo) {
this.name=name;
this.stuNo=stuNo;
}
@Override
public String toString() {
return "Student [name=" + name + ", stuNo=" + stuNo + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((stuNo == null) ? 0 : stuNo.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (stuNo == null) {
if (other.stuNo != null)
return false;
} else if (!stuNo.equals(other.stuNo))
return false;
return true;
}
}
HashMap的代码实现
Map<Student,String> map=new HashMap<Student, String>();
Student s1=new Student("小明","123");
Student s2=new Student("小华","234");
Student s3=new Student("小花","456");
map.put(s1, "重庆");
map.put(s2, "上海");
map.put(s3, "湖南");
map.put(new Student("小明","123"), "重庆");
System.out.println(map.size());
System.out.println(map.toString());
map.remove(s1);
//遍历
for (Student key : map.keySet()) {
System.out.println(key+"-----------" +map.get(key));
}
for (Map.Entry<Student, String> entry:map.entrySet()) {
System.out.println(entry.getKey()+"------"+entry.getValue());
}
//判断
System.out.println(map.containsKey(s1));
System.out.println(map.containsValue("上海"));
HashTable (了解)
TreeMap
特点
实现了SortedMap接口(是Map的子接口) ,可以对key自动排序
代码实现
Map<Student,String> map=new TreeMap<Student, String>();
Student s1=new Student("小明","123");
Student s2=new Student("小华","234");
Student s3=new Student("小花","456");
map.put(s1, "重庆");
map.put(s2, "上海");
map.put(s3, "湖南");
map.put(new Student("小明","123"), "重庆");
System.out.println(map.size());
System.out.println(map.toString());
运行结果:
Exception in thread “main” java.lang.ClassCastException: maps.Student cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(TreeMap.java:1294)
at java.util.TreeMap.put(TreeMap.java:538)
at maps.Dome.main(Dome.java:13)
//此报错是因为Student不能进行比较,因此不能进行排序,便可报错可参考前方TreeSet
解决方法1,让其在Student类继承comparable类,重写compareTo进行name和age的比较便可
Student类的代码实现
package maps;
public class Student implements Comparable<Student>{
private String name;
private String stuNo;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStuNo() {
return stuNo;
}
public void setStuNo(String stuNo) {
this.stuNo = stuNo;
}
public Student() {
// TODO Auto-generated constructor stub
}
public Student(String name,String stuNo) {
this.name=name;
this.stuNo=stuNo;
}
@Override
public String toString() {
return "Student [name=" + name + ", stuNo=" + stuNo + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((stuNo == null) ? 0 : stuNo.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (stuNo == null) {
if (other.stuNo != null)
return false;
} else if (!stuNo.equals(other.stuNo))
return false;
return true;
}
@Override
public int compareTo(Student o) {
int n1=this.name.compareTo(o.getName());
int n2=this.stuNo.compareTo(o.getStuNo());
return n1==0?n2:n1;
}
}
解决方法2,直接在TreeMap中写comparable的匿名类即可,进行姓名和学号的比较(称为定制比较)
Map<Student,String> map=new TreeMap<Student, String>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int n1=o1.getName().compareTo(o2.getName());
int n2=o2.getStuNo().compareTo(o2.getStuNo());
return n1==0?n2:n1;
}
});
Student s1=new Student("小明","123");
Student s2=new Student("小华","234");
Student s3=new Student("小花","456");
map.put(s1, "重庆");
map.put(s2, "上海");
map.put(s3, "湖南");
map.put(new Student("小明","123"), "重庆");
System.out.println(map.size());
System.out.println(map.toString());
map.remove(s1);
//遍历
for (Student key : map.keySet()) {
System.out.println(key+"-----------" +map.get(key));
}
for (Map.Entry<Student, String> entry:map.entrySet()) {
System.out.println(entry.getKey()+"------"+entry.getValue());
}
//判断
System.out.println(map.containsKey(s1));
System.out.println(map.containsValue("上海"));
Collections工具类
List<Integer> list=new ArrayList<Integer>();
list.add(200);
list.add(20);
list.add(22);
list.add(2);
list.add(39);
list.add(23);
//sor排序
System.out.println("排序前"+list);
Collections.sort(list);
System.out.println("排序后"+list);
//binarySearch 二分查找
int i=Collections.binarySearch(list, 12);
System.out.println(i);
//copy 复制
List<Integer> dest=new ArrayList<Integer>();
for (int j = 0; j < list.size(); j++) {
dest.add(0);
}
Collections.copy(dest, list);
System.out.println(dest.toString());
//reverse 反转
Collections.reverse(list);
System.out.println("反转之后"+list);
//shuffle 打乱
Collections.shuffle(list);
System.out.println("打乱之后"+list);
//补充 list转成数组
Integer [] arr= list.toArray(new Integer[0]);
System.out.println(Arrays.toString(arr));
//数组转换成集合
String [] names= {"张三","李四","王五"};
//集合是一个受限集合,不能添加和删除
List<String> list2=Arrays.asList(names);
System.out.println(list2);