JAVA9Collection1.docx
《JAVA9Collection1.docx》由会员分享,可在线阅读,更多相关《JAVA9Collection1.docx(16页珍藏版)》请在冰豆网上搜索。
![JAVA9Collection1.docx](https://file1.bdocx.com/fileroot1/2023-1/29/0e6bdbfc-8bbd-4a03-a3c2-e8dd86d8b404/0e6bdbfc-8bbd-4a03-a3c2-e8dd86d8b4041.gif)
JAVA9Collection1
JAVA基础
集合
Collection
•集合与数组的区别:
1.数组元素可以是基本类型值也可以是对象,集合里只能保存对象(即不能保存基本数据类型数据)
2.数组长度不可改变,而集合没有长度约束
importjava.util.ArrayList;
importjava.util.Collection;
importjava.util.Iterator;
publicclassCollectionDemo{
publicstaticvoidmain(String[]args){
//ctrl+shift+o导包
//ArrayListextendsAbstractListimplementsList
//ListextendsCollection(接口继承)
//黄色波浪线表示的是警告,这里没有指定泛型,所以有黄色波浪线警告
Collectioncollection=newArrayList();
//添加元素,添加成功返回true
System.out.println(collection.add("123"));
System.out.println(collection.add(newStudent("张三","上海市")));
//集合的大小,即集合添加了多少个元素
System.out.println(collection.size());
//输出集合信息
System.out.println(collection.toString());
//将一个集合添加到另一个调用的集合中
System.out.println(collection.addAll(collection));
System.out.println(collection.size());//4
collection.clear();
System.out.println(collection.size());//0
System.out.println(null==collection);//false
System.out.println(collection.isEmpty());//true
System.out.println(collection.add(newStudent("张三","上海市")));
//false集合中存储的是对应的引用,这里通过new创建出来的内容,虽然在值上相同
//但是只要new就会在堆中重新分配地址空间,引用(地址)自然不同
System.out.println(collection.contains(newStudent("张三","上海市")));
Studentstu=newStudent("李四","苏州市");
//此时集合中共2个元素
collection.add(stu);
//true前后两个对象地址相同
System.out.println(collection.contains(stu));
//不可以删除,因为他们地址不一致
System.out.println(collection.remove(newStudent("李四","苏州市")));
//可以删除,因为添加与删除时同一个对象,地址相同
//System.out.println(collection.remove(stu));
System.out.println(collection.size());
System.out.println(collection.add("123"));
//不要只看表面上的实现,一定要挖掘出他内部的实现逻辑,
//只有这样在发生问题时,才能够很好分析与定位问题
//即这里的for-each循环中的obj实际调用的是其指向子类的toString方法
Object[]objs=collection.toArray();
for(Objectobj:
objs){
System.out.println(obj.toString());
}
System.out.println("=========================");
//迭代器,Iterator遍历集合,以后会经常用到,只能向后遍历
Iteratoriterator=collection.iterator();
//hasNext是否有下一个元素,有则返回true,否则返回false
//next指针移到下一个元素,并返回相应的元素值
while(iterator.hasNext()){
Objectobj=iterator.next();
if(objinstanceofStudent){
Studentstu1=(Student)obj;
stu1.setName("王五");
}
}
//因为iterator只能向后遍历,所以在此需要新建一个迭代器对象,
//而不能使用原来的迭代器对象,就是上面的iterator
Iteratoriterator1=collection.iterator();
while(iterator1.hasNext()){
System.out.println("-----");
System.out.println(iterator1.next());
}
System.out.println("_______________");
//for-each循环遍历
for(Objectobj:
collection){
System.out.println(obj);
}
}
}
ArrayList
List:
有序(添加顺序与存储顺序相同)、允许重复的集合
importjava.util.ArrayList;
importjava.util.List;
importjava.util.ListIterator;
publicclassGenericColecDemo{
publicstaticvoidmain(String[]args){
//alt+shift+r重命名变量,会修改同一作用域的所有这个变量
Listlist=newArrayList();
//对象的默认值就是null,所以可以添加
list.add(null);
System.out.println(list.size());
list.add(newStudent("张三","上海市"));
System.out.println(list.size());
list.clear();
System.out.println(list.isEmpty());
Studentstu=newStudent("李四","上海市");
//可以添加重复元素
list.add(stu);
list.add(stu);
list.add(newStudent("张三","上海市"));
list.add(newStudent("王五","苏州市"));
System.out.println(list.size());
//ArrayList是有序集合,什么是有序?
//添加顺序与存储顺序一致(遍历顺序)
//Iteratorite=list.iterator();
//ListIteratorextendsIterator
ListIteratorite=list.listIterator();
while(ite.hasNext()){
System.out.println(ite.next());
}
System.out.println("********************");
//hasPrevious前面是否有元素
while(ite.hasPrevious()){
//指向前一个,并获取元素
System.out.println(ite.previous());
}
System.out.println("********************");
System.out.println(list.get(0));
//for循环遍历
for(inti=0;iSystem.out.println(list.get(i));
}
//for-each循环遍历自己写
System.out.println("===================");
//下标从0开始,删除指定位置的元素,返回被删除的元素
//当下标>=数组大小时,报出java.lang.IndexOutOfBoundsException
//Studentstu1=list.remove(10);
Studentstu1=list.remove
(2);
System.out.println(stu1);
System.out.println("====================");
Studentstu2=newStudent("赵六","南京市");
//下标大于集合的大小或小于0会抛出异常IndexOutOfBoundsException
list.add(3,stu2);//insert
for(inti=0;iSystem.out.println(list.get(i));
}
System.out.println(list.indexOf(stu2));//3
System.out.println(list.indexOf(newStudent("赵六","南京市")));//-1
Studentstu3=newStudent("刘七","南京市");
list.set(3,stu3);//replace
System.out.println("====================");
for(inti=0;iSystem.out.println(list.get(i));
}
//集合中常用
//方法:
getsizeaddremoveclearisEmptyIterator(ListIterator、for、for-each)
//注意判断的先后顺序(&&的短落操作)
if(null!
=list&&!
list.isEmpty()){
//对集合操作
}
}
}
HashSet
Set:
无序(添加顺序与存储顺序不同,hashcode/地址)、不可重复的集合
Set集合不允许包含相同的元素,如果试图把两个相同的元素加入同一个Set集合中,则添加失败,add方法返回false,且新元素不会被加入
HashSet按Hash算法来存储集合中的元素,因此具有很好的存取和查找性能
•HashSet集合判断两个元素相等的标准是:
两个对象的hashCode()方法返回值相等,并且两个对象通过equals方法比较相等。
注意:
如果需要把一个对象放入HashSet中时,如果重写该对象对应类的equals()方法,也应该重写其hashCode()方法,其规则是:
如果2个对象通过equals方法比较返回true时,这两个对象的hashCode也应当相同
publicclassStudentimplementsComparable{
privateStringname;
privateStringaddress;
privateintsno;
publicStudent(){
super();
//TODOAuto-generatedconstructorstub
}
publicStudent(Stringname,Stringaddress){
super();
this.name=name;
this.address=address;
}
publicStudent(Stringname,Stringaddress,intsno){
super();
this.name=name;
this.address=address;
this.sno=sno;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicStringgetAddress(){
returnaddress;
}
publicvoidsetAddress(Stringaddress){
this.address=address;
}
//@Override
//publicinthashCode(){
//finalintprime=31;
//intresult=1;
//result=prime*result+((address==null)?
0:
address.hashCode());
//result=prime*result+((name==null)?
0:
name.hashCode());
//returnresult;
//}
//@Override
//publicbooleanequals(Objectobj){
//if(this==obj)
//returntrue;
//if(obj==null)
//returnfalse;
//if(getClass()!
=obj.getClass())
//returnfalse;
//Studentother=(Student)obj;
//if(address==null){
//if(other.address!
=null)
//returnfalse;
//}elseif(!
address.equals(other.address))
//returnfalse;
//if(name==null){
//if(other.name!
=null)
//returnfalse;
//}elseif(!
name.equals(other.name))
//returnfalse;
//returntrue;
//}
//添加元素时自动执行,不用手动调用
//直接返回一个整数值,升序为正降序为负,升序降序是以添加元素顺序为基准
//
@Override
publicintcompareTo(Studento){
//System.out.println("---"+this);
//根据实体属性进行排序,比较时this在前表示升序,this在后表示降序
returnthis.sno-o.sno;//pareTo(this.name)
}
@Override
publicStringtoString(){
return"Student[name="+name+",address="+address+",sno="+sno+"]";
}
//10个人的团队,学生类已经有了排序规则,为大家都来调用
//现在你有个需求,不要默认已经提供的排序,需要一个按照名字的排序
//现在怎么做?
//改默认排序(一定不行,这么做没有团队意识)
//创建treeset自定义排序(可取的)
}
/**
*Set集合不允许包含相同的元素,如果试图把两个相同的元素加入同一个Set集合中,则添加失败,add方法返回false,且新元素不会被加入
*
*HashSet按Hash算法来存储集合中的元素(为什么是无序的),因此具有很好的存取和查找性能
*
*HashSet集合元素可以使null
*
*@authortzhang
*
*/
publicclassHashSetDemo{
publicstaticvoidmain(String[]args){
//每次new都会新开辟存储空间存储对象
Studentstu1=newStudent("张三","上海市");
Studentstu2=newStudent("张三","上海市");
//HashSetextendsAbstractSetimplementsSet
//SetextendsCollection
SetsetStu=newHashSet();//LinkedHashSet
//没有元素,可以直接添加成功
setStu.add(stu1);
//会将stu2元素的hashcode值与已存在的元素的hashcode值进行比较
//如果hashcode值与他们都不相同,就直接添加进来,添加成供
//如果hashcode值与他们比较,有与他相同的值,那么再比较这两个元素的equals方法
//如果equals方法返回值为true,那么就添加失败
//如果equals方法返回值为false,那么就添加成功,
//(hashcode值相同,但是equals返回false,这种情况尽量不要发生)
//这样会导致HashSet性能下降
setStu.add(stu2);
//赋值操作不会在堆中新开辟存储空,只是将变量的引用指向了一块已经存在的空间
Studentstu3=stu2;
setStu.add(stu3);
System.out.println(setStu.size());
//为什么没有与索引相关的操作方法?
//因为set是存储是无序的,无序就是添加的顺序与遍历输出的顺序不一致
Studentstu4=newStudent("王五","上海市");
Studentstu5=newStudent("赵六","上海市");
Studentstu6=newStudent("刘七","上海市");
Studentstu7=newStudent("李四","上海市");
setStu.add(stu4);
setStu.add(stu5);
setStu.add(stu6);
setStu.add(stu7);
System.out.println("==========================");
for(Studentstu:
setStu){
//观察输出数据,可以看到添加顺序与输出顺序不一致
System.out.println(stu);
}
System.out.println("==========================");
Iteratorite=setStu.iterator();
while(ite.hasNext()){
System.out.println(ite.next());
}
}
}
TreeSet
•TreeSet判断两个对象不相等的标准是:
1.两个对象通过equals方法比较返回false
2.通过compareTo(Objectobj)比较没有返回0(即使是同一个对象,compareTo方法返回0就认为他们相等)
向TreeSet中添加的应该是同一个类的对象,否则也传给引发上面的异常
注意:
如果试图把一个对象添加进TreeSet时,则该对象的类必须实现Comparable接口,否则程序将会抛出ClassCastException异常。
•定制排序
TreeSet的自然排序是根据集合元素的大小,TreeSet将它们以升序排列。
如果需要实现定制排序,如降序,则可以使用Comparator接口的帮助。
Comparator接口中包含一个intcompareTo(To1,To2)方法以,用于比较o1和o2的大小:
1.返回正整数,则表明o1大于o2;
2.返回零,则表明o1等于o2
3.返回负整数,则表明o1小于o2
如果需要实现定制排序,则需要在创建TreeSet集合对象时,并提供一个Comparator对象与该TreeSet集合关联,由该Comparator对象负责集合元素的排序逻辑。
importjava.util.Comparator;
importjava.util.Iterator;
importjava.util.SortedSet;
importjava.util.TreeSet;
publicclassTreeSetDemo{
publicstaticvoidmain(String[]args){
//TreeSetextendsAbstractSetimplementsNavigableSet
//NavigableSetextendsSortedSetextendsSet
//可以自定义排序规则的集合,排序的对象要实现Compare