java基础-集合框架

体系概述

特点

  • 存储对象
  • 长度可变
  • 不能存储基本类型

体系图

集合

共性方法(常用)

1.添加
boolean add(Object obt)
boolean addAll(Collection coll)
2.删除
boolean remove(Object obj)
boolean removeAll(Collection coll)
void clear()
3.判断
boolean contains(Object obj)
boolean containsAll(Collection coll)
boolean isEmpty()
4.获取
int size()
iterator()
5.其他
boolean retainAll(Collection coll)//取交集
Object [] toArray()//集合转成数组

迭代器

Iterator

1.boolean hasNext():如果迭代具有更多的元素,则返回true。
2.E next():返回迭代中的下一个元素。超出则抛出异常NoSuchElementException 
//代码段
Collection coll = new ArrayList();
coll.add("a");
coll.add("b");
Iterator it = coll.iterator();
while(it.hasNext()){
    system.out.print(it.next());
}

注意:此方法一般只用于迭代元素,不要在迭代过程中操作集合的元素,容易抛出异常。

while(it.hasNext()) {
	Object obj = it.next();
	if(obj.equals("b")){
		collection.add("abc9");
	}else {
		System.out.println("next:"+obj);
	}
}
//java.util.ConcurrentModificationException

ListIterator

  • List集合特有的
  • 常用方法
1.正向遍历
  boolean hasNext()
  E next()
  int nextIndex():返回随后调用next()返回的元素的索引。 
2.逆向遍历
  boolean hasPrevious()
  E previous()
  int previousIndex():返回由后续调用previous()返回的元素的索引。
3.操作元素
  add(E e)
  set(E e)
  remove()
代码:
List list = new ArrayList();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
ListIterator listIterator = list.listIterator();
while(listIterator.hasNext()) {
	Object obj= listIterator.next();
	if(obj.equals("c")) {
		//listIterator.add("asda");
		listIterator.set("asda");
	}
	
}
System.out.println(list);

List集合

  • 有序:存入和取出的顺序一致
  • 索引:元素有索引
  • 重复:存储的元素可以重复

常用方法

  • 添加
void add(index,element)
void add(index,collection)
  • 删除
Object remove(index)
  • 修改
Object set(index,element)
  • 获取
Object get(index)
int indexOf(object):返回此列表中指定元素的第一次出现的索引,如果此列表不包含元素,则返回-1。 
List subList(from,to);

代码

List list = new ArrayList();
list.add("a");
list.add("b");
list.add("c");
System.out.println(list);
//添加
list.add(2,"d");
list.add(2,list2);//list2自己在定义一个
//删除
System.out.println(list.remove(1));
//修改
list.set(0,"z");
//获取
list.get(1);

LinkedList

  • 特点:增删快

常用方法

//增加
addFirst();
addLast():
offerFirst();
offetLast();
//获取
getFirst();.//获取但不移除,如果链表为空,抛出NoSuchElementException.
getLast();
peekFirst();//获取但不移除,如果链表为空,返回null.
peekLast():
//删除
removeFirst();//获取并移除,如果链表为空,抛出NoSuchElementException.
removeLast();
pollFirst();//获取并移除,如果链表为空,返回null.
pollLast();

arrayList

  • 特点:非同步,查询速度快
  • 需求:定义一个功能取出ArrayList中重复的元素
public static ArrayList getSingleElement(ArrayList list) {
    //1.定义一个临时容器
    List tempList = new ArrayList();
    //2.迭代元素
    ListIterator lit = list.listIterator();
    while(lit.hasNext()){
        Object obj = it.next();
        //3.判断元素是否存在临时容器中
        if(!tempList.contains(obj)){
            tempList.add(obj);
        }
    }
    //4.返回集合
    return tempList
}

Vector

  • 特点:线程安全,效率低

Set集合

  • 唯一:存储的数据不能重复
  • 无序:输出的顺序是无序的

HashSet

  • 特点:内部数据结构是哈希表 ,是不同步的。
  • 对于自定义的类需要重写hashCode()和equals()

LinkedHashSet

  • 特点:输入输出顺序一致;保证唯一

TreeSet

  • 特点:可以对Set集合中的元素进行排序。是不同步的。

自定义类需要定义比较规则

  • 实现Comparable接口,重写compareTo();类中所有属性都必须写进排序规则;
  • 定义比较器Comparator,重写compare();
  • bean类实现Comparable接口
public class Person implements Comparable {
	private String name;
	private int age;
	public Person() {
		super();
	}
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	@Override
	public int hashCode() {
		return name.hashCode()+age*27;
	}
	@Override
	public boolean equals(Object obj) {
		if(this == obj)
			return true;
		if(!(obj instanceof Person))
			throw new ClassCastException("类型错误");
		Person p = (Person)obj;
		return this.name.equals(p.name) && this.age == p.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;
	}
	public String toString(){
		return name+":"+age;
	}
	@Override
	public int compareTo(Object o) {
		Person p = (Person)o;
		if(this.age>p.age)
			return 1;
		if(this.age<p.age)
			return -1;	
		else{
			return this.name.compareTo(p.name);
		}
	}
}
  • 定义比较器
public class ComparatorByName implements Comparator<Object> {
	@Override
	public int compare(Object o1, Object o2) {
		Person p1 = (Person)o1;
		Person p2 = (Person)o2;
		int temp = p1.getName().compareTo(p2.getName());
		return temp==0?p1.getAge()-p2.getAge(): temp;
	}

}

//在通过TreeSet的构造函数将比较器传进去
TreeSet ts = new TreeSet(new ComparatorByName());

给非同步加锁变同步(ArrayList)

//1.定义一个内部类实现List集合
//2.往ArrayList的一些异步方法加同步
class MyCollections{
	public static  List synList(List list){
		return new MyList(list);
	}
	private class MyList implements List{
    	private List list;
    	private static final Object lock = new Object();
    	MyList(List list){	
    		this.list = list;	
    	}
    	public boolean add(Object obj){
    		synchronized(lock)
    		{
    			return list.add(obj);
    		}
    	}
    }
}
//---------------------------------------------
List list = new ArrayList()
List myList = MyCollections.synList(list)

Map集合

  • 双列集合,以键值对的形式存储;
  • 键值唯一

常用方法

1.添加
put(key,value)
2.删除
void  clear():清空map集合。
value remove(key):根据指定的key翻出这个键值对。 
3.获取
get(key)
4.其他
Set<K> keySet():将Map的key值以set的方式存储
Set<Map.Entry<K,V>> entrySet():将Map集合变为Set集合
  • 迭代取出Map集合。

keySet()

//将key值存入Set集合,在使用Iterator迭代器,通过get(key)来取出元素
Map map = new HashMap();
map.put(8,"zhaoliu");
map.put(2,"zhaoliu");
map.put(7,"xiaoqiang");
map.put(6,"wangcai");
Set mapSet = map.keySet();
Iterator it = mapSet.iterator();
while(it.hasNext()){
    Object objKey = it.next();
    System.out.println("key值:"+objKey+"    value值:"+map.get(objKey));
}

entrySet()

  • getKey()
  • getValue()
Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
Iterator<Map.Entry<Integer, String>> it = entrySet.iterator();
while(it.hasNext()){
	Map.Entry<Integer, String> me = it.next();
	Integer key = me.getKey();
	String value = me.getValue();
	System.out.println(key+"::::"+value);
}

//如何理解Map.Entry?
interface MyMap{
	public static interface MyEntry{//内部接口
		void get();
	}
}
class MyDemo implements MyMap.MyEntry{
	public void get(){}
}
  • Map.Entry其实就是静态内部接口

HashMap

  • 内部结构是哈希表,不是同步的。允许null作为键,null作为值。
  • 需求:将学生对象和学生的归属地通过键与值存储到map集合中。
HashMap<Student,String> hm = new HashMap<Student,String>();
hm.put(new Student("lisi",38),"北京");
hm.put(new Student("zhaoliu",24),"上海");
hm.put(new Student("xiaoqiang",31),"沈阳");
hm.put(new Student("wangcai",28),"大连");
hm.put(new Student("zhaoliu",24),"铁岭");
Iterator<Student> it = hm.keySet().iterator();
while(it.hasNext()){
	Student key = it.next();
	String value = hm.get(key);
	System.out.println(key.getName()+":"+key.getAge()+"---"+value);
}

LinkedHashMap

  • 保证输入顺序和输出顺序一致
HashMap<Integer,String> hm = new LinkedHashMap<Integer,String>();
hm.put(7, "zhouqi");
hm.put(3, "zhangsan");
hm.put(1, "qianyi");
hm.put(5, "wangwu");
Iterator<Map.Entry<Integer,String>> it = hm.entrySet().iterator();
while(it.hasNext()){
	Map.Entry<Integer,String> me = it.next();
	Integer key = me.getKey();
	String value = me.getValue();
	System.out.println(key+":"+value);
}

HashTable

  • 内部结构是哈希表,是同步的。不允许null作为键,null作为值。

TreeMap

  • 内部结构是二叉树,不是同步的。可以对Map集合中的键进行排序。
  • 需求二:在需求一的基础上依次根据姓名首字母、年龄排序输出
TreeMap<Student,String> tm = new TreeMap<Student,String>(new ComparatorByName());
tm.put(new Student("lisi",38),"北京");
tm.put(new Student("zhaoliu",24),"上海");
tm.put(new Student("xiaoqiang",31),"沈阳");
tm.put(new Student("wangcai",28),"大连");
tm.put(new Student("zhaoliu",24),"铁岭");
Iterator<Map.Entry<Student, String>> it = tm.entrySet().iterator();
while(it.hasNext()){
	Map.Entry<Student,String> me = it.next();
	Student key = me.getKey();
	String value = me.getValue();
	System.out.println(key.getName()+":"+key.getAge()+"---"+value);
}

Collections

  • 集合操作类
  • sort(list,比较器)

Arrays

  • asList:数组转集合
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值