Java-集合

集合

  

集合概念

   对象的容器,实现了对对象常用的操作方法。可实现数组的功能。(java.util.*)

和数组的区别:

  1)数组长度固定,集合长度不固定;
  2)数组可以存储基本类型和引用类型,集合只能存储引用类型。

Collection 体系集合

在这里插入图片描述

Collection 父接口

   特点:代表一组任意类型的对象,无序,无下标,不能重复
   方法:
   1)boolean add(Object obj) //添加一个对象;
   2)boolean addAll(Collection c) //将一个集合中的所有对象添加到此集合中;
   3)void clear() //清空此集合中的所有对象;
   4)boolean contains(Object o) //检查此集合中是否包含o对象;
   5)boolean equals(Object o) //比较此集合是否与指定对象相等;
   6)boolean isEmpty() //判断此集合是否为空;
   7)int size() //返回此集合中的元素个数;
   8)boolean remove(Object o) //在此集合中移除o对象;
   9)Object[] toArray() //将此集合转换成数组;

Collection 使用

/**
* (添加元素)
* 删除元素
* 遍历元素
* 判断元素
*/
public class Demo1{
	public static void main(String[] args){
		Collection collection=new ArrayList();
		// (1)添加元素
		collection.add("apple");
		collection.add("banana");
		System.out.println("元素个数"+collection.size());
		// (2)删除元素
		collection.remove("apple");
		System.out.println("元素个数"+collection.size());
		// (3)遍历元素【重点】
		// (3.1)使用增强for
		for(Object object:collection){
			System.out.println(object);
		}
		// (3.2) 使用迭代器(专门用来遍历集合的一种方式)
		Iterator it=collection.iterator();
		while(it.hasNext()){
			String ob=(String)it.next();
			System.out.println(ob);
			it.remove();
		}
		// 判断元素
		
		System.out.println(collection.contains("apple"));
		System.out.println(collection.isEmpty());
		
		
	}
}
迭代器Iterator

   1)hasNext(); //有没有下一个元素
   2)next(); //获取下一个元素
   3)remove(); //删除当前元素。当使用迭代器的时候,并不能使用collection的其它方法来改变元素的。(并发修改)

使用2

  新建Student类

public class Student{
	private String name;
	private int age;
	public Student(){
	}
	public Student(String name, int age){
		super();
		this.name=name;
		this.age=age;
	}
	public String getName(){
		return name;
	}
	public int getAge(){
		return age;
	}
	public void setName(String name){
		this.name=name;
	}
	public void setAge(int age){
		this.age=age;
	}
	@Override
	public String toString(){
		return "Student [name="+name+",age="+age+"]";
	}
}

  测试Demo2

public class Demo2{
	public static void main(String[] args){
		Collection col=new ArrayList();
		Student s1=new Student("张三",18);
		Student s2=new Student("张1",12);
		Student s3=new Student("张2",11);
		Student s4=new Student("张4",19);
		col.add(s1);
		col.add(s2);
		col.add(s3);
		col.add(s4);
		System.out.println("元素个数"+col.size());
		System.out.println(col.toString());
		col.remove(new Student("张三"22); //并不能删除之前的张三
		// 清除
		col.clear();
		//遍历
		for(Object obj:col){
			Student s=(Student) obj;
			System.out.println(s);
		}
		Iterater iterater=col.iterator();
		while(iterator.hasNext()){
			Student s=(Student)iterator.next();
			System.out.println(s);
		}
		
		System.out.println(col.contains(s1));
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值