JAVA -第七章 集合(一)

来源:互联网 发布:淘宝定制服装 编辑:程序博客网 时间:2024/05/22 03:51

Collection 接口 及一些方法

1.存储对象可以考虑① 数组② 集合
2.数组存储对象的特点:studnet[] stu=new studnet[20]….stu[0]=new Student()..

弊端1:一旦创建其长度不可变。
3.集合
Collection 接口
|…..List接口:存储有序的,可以重复的元素
|..ArrayList,LinkedList,Vector
|…..Set接口:存储无序的,不可重复的元素。
|….HashSet,LinkedHashSet,TreeSet
Map接口,存储“键-值”对的数据
|….HashMap,LinkedHashMap,TreeMap,Hashtable(子类-Properties)

弊端2:真实的数组存放的个数是不可知的

Collection接口“

Set 元素无序,不可重复的集合。类似于高中的“集合”
List:元素有序,可重复的集合。-“动态”数组
Map接口:具有映射关系“key-value”的集合
类似于高中的y-f(x)(x1,y1)(x2y2)
对象的用包装类
Collection coll=new ArrayList();
1.size():返回集合元素个数
**2..**add(Object obj);向集合中添加一个元素
**3.**addAll(Collection coll);将形参coll中包含的所有元素添加到当前集合中
Collection coll1=Arrays.asList(1,2,3);//是数组转换为集合
coll.addAll(coll1);
System.out.println(call.size());
//查看集合元素
System.out.println(coll);
4.isEmpty():判断集合是否为空
System.out.println(coll.isEmpty());
5.clear():清空集合元素
coll.clear();
6.contains(Object obj):判断集合中是否包含指定的obj元素,如果包含返回true 反之返回false
判断的依据;根据元素所在的类的equals()方法进行判断。
明确:如果存入集合中的元素是自定义类的对象,要求自定义重写equals()方法。
boolean b1=cool.contains(123);
System.out.prinln(b1);
//自定义一个类
person p=new person(“AA”,23);
coll.add(p);
boolean b2=cool.contains(p)//实现结果为true
如果是
cool.add(new person(“AA”,23));
boolean b3=cool.contains(new person(“AA”,23));//其实实现的是false 因为是俩个对象 地址值不同
要想让其结果为true 则的对person重写
7.containsAll(collection coll):判断当前集合中是否包含coll中的所有元素
Collection coll1= Array.asList();
coll1.add(“AA);
coll1.add(123);
coll1.add(new String(“AA”));
boolean b4=cool.containsAll(cool1);
System.out.println(“#”+b4);
coll1.add(456);
8.retainAll(Colection coll);当前集合与coll的共有集合,返回给当前集合。
coll.retainAll(coll1);
System.out.prinltn(coll);
9.remove(Object obj)删除集合中的obj元素,若删除成功返回true 否则返回false
**10.**removeAll(coll1)从当前集合中删除包含coll的元素;
coll.removeAll(coll1);
boolean b5=coll.remove(“BB”);
System.out.println(b5);
11.equals(IObject obj);判断集合中的所有元素是否完全相同。
Collection coll2= Array.asList();
coll2.add(“AA);
coll2.add(123);
System.out.println(coll1.equals(coll2));
12.hashCode();
System.out,.println(coll.hashCode());
13.toArray()将集合转化为数组
Object[] obj=coll.toArray();
for(int i=0;i < obj.length;i++){
System.out.oprintln(obj[i]);
}
14.iterator()返回一个Iterator接口实现类的对象,进而实现集合的遍历!
Iterator iterator=coll.iterator();
方式一:System.out.println(iterator.next());
方式二:for(int i;i< coll.size();i++){
System.out.println(iterator.next());
}
方式三(最佳)使用迭代器Iterator实现集合的遍历
while(iterator.hasNext()){
System.out.println(iterator.next());
}
错误的写法
while((i.next())!=null){
System.out.println(i.next());
使用增强的for循环实现集合的遍历
for(Object i:coll){
System.out.println(i);
}
使用增强for循环实现对数组的遍历
public void test1(){
String[] str=new String[]{“AA”,”BB”,”cc”};
for(String s:str){
System.out.println(s);
}
}