集合

1、集合概述

数组长度是固定的,如果要改变数组的长度需要创建新的数组将旧数组里面的元素拷贝过去,使用起来不方便。

java给开发者提供了一些集合类,能够存储任意长度的对象,长度可以随着元素的增加而增加,随着元素的减少而减少,使用起来方便一些。

集合知识总结

**Collection**
		  List(存取有序,有索引,可以重复)
		  		ArrayList:底层是数组实现,线程不安全,查找和修改快,增和删除慢
			
				LinkedList:底层是链表实现,线程不安全,增和删除比较快,查找和修改慢

			    Vector :底层是数组实现  的,线程安全的,无论增删查改都慢 
       
		           如果查找和修改多,用ArrayList
		           如果增和删多,用LinkedList
		           如果都多,用ArrayList.



          Set(存取无序,无索引,不可以重复)
          		
          		HashSet:底层是哈希算法实现

			   LinkedHashSet:底层是链表实现,可以保证元素唯一,存取顺序一致
				
				TreeSet:底层是二叉树算法实现,可以排序,存储自定义类型时   需要注意实现Comparable接口并重写compareTo方法
			
			一般在开发的时候不需要对存储的元素排序,所以在开发的时候大多用HashSet,HashSet的效率比较高。TreeSet在面试的时候比较多。


			Map(键值)
				HashMap:底层是哈希算法
					
				LinkedHashMap:底层是链表,存取顺序一致
				
			   TreeMap:底层是二叉树算法,可以排序

集合继承体系图
java提供了一些集合类,这些集合类分别适用于不同的场景,下面是常用的一些集合基础体系图。
在这里插入图片描述
里面的Collection是接口,下面的List、Set、Queue也都是接口,并且继承了这个Collection。最下面的 ArrayList、LinkedList、Vector、HashSet、TreeSet、PriorityQueue都是它们的实现类。

集合类的一些特点
List: 里面存放的数据是有顺序的,可以存放重复的数据

Set:里面存放的数据是没有顺序的,不能存放重复的数据

Queue:是一个队列,里面的数据先进先出,可以存放重复的数据

数组与集合的区别

  • 区别1:
    数组既可以存储基本数据类型,又可以存储引用数据,基本数据类型存储的是值,引用数据类型存储的是地址值

     	集合只能存储引用数据类型(对象),如果存储基本数据类型时,会自动封装变成相应的包装类
    
  • 区别2:
    数组的长度是固定的,不能自动增长的
    集合的长度是可变的,可以根据元素的增长而自动增长

1.1Collection常用方法

注意 使用 Collection 为接口,在使用的时候,需要 使用多态的方法。

使用集合存储String类型:

Collection类
					java.lang.Object
						java.util.AbstractCollection<E>
						
			This class provides a skeletal implementation of the Collection interface ,to minimize the effort required to implement this interface。
package com.Collection;

import java.util.ArrayList;
import java.util.Collection;

 对象方法:
			 			add(E e)  :Ensures that this collection contains the specified element(optional operation)。
			 			
			 			contains(Object o): Returns true if this collection contains the specified element;若新建类需要重写其中的equals方法
			 			
			 			clear()  :Removes all of the elements from this collection
			 			
			 			remove(Object o):Removes a single instance of the specified element from this collection,if it is present.
			 			
			 			isEmpty()
			 			
			 			size()  :Returns the number of elements in this selection
			 			
			 			toArray() :Returns an array containning all of the elements in this collection
			 			
			 			iterator():Returns an iterator over the elements contained in this collection.
			 			
			 			addAll(Collection<?extends E> c):Adds all of the 
			 			
			 
			 
			Interface Iterator<E> 
			对象方法:
					hasNext()  //Returns true if the iteration has more elements
					
					next()   //Returns the next element in the iteration
					

public class CollectionTest {

	public static void main(String[] args) {
	//		Collection<String> c = new ArrayList<>();
//		
//		c.add("a");
//		c.add("b");
//		c.add("c");
//		c.add("d");
//		
//		System.out.println(c);		//[a, b, c, d]
//
//		System.out.println(c.size()); //4
//		
//		System.out.println(c.contains("a"));//true
//		
//		System.out.println(c.isEmpty()); //false
//		
//		c.remove("a");
//		System.out.println(c);		//[ b, c, d]
//		
		c.clear();
		System.out.println(c);		//[]
//		
//		//转换成数组,并输出
//		Object[] st = c.toArray();
//		for(int i =0;i<st.length;i++) {
//			System.out.println(st[i]);
//		}
//		System.out.println("****************************");
//		
//		//转化成迭代器的方式并输出
//		Iterator<String>  itr= c.iterator();
//		while(itr.hasNext()) {
//			System.out.println(itr.next());
//		}
//		
//		
		

使用集合存储自己创建的Person类型:
创建一个Person类

package com.Collection;
/*
 * 
 * 自己创建的Person类
 */
public class Person {
	
	private int age;
	private String name;
	
	public Person(int age, String name) {
		super();
		this.age = age;
		this.name = name;
	}

	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override //重写toString方法否则打印的时候会出现问题
	public String toString() {
		return "Person [age=" + age + ", name=" + name + "]";
	}

	/**
	 * @return the age
	 */
	public int getAge() {
		return age;
	}

	/**
	 * @param age the age to set
	 */
	public void setAge(int age) {
		this.age = age;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	
	
	@Override //重写equals方法
	public boolean equals(Object obj) {
		if(obj == this) {
			return true;
		}
		if(obj instanceof Person) {
			Person p =(Person)obj;
			if(p.age==age & p.name.equals(name)) {
				return true;
			}
		}
			return false;
	}
	
}

创建测试类:

package com.Collection;

import java.util.ArrayList;
import java.util.Collection;

public class PersonTest {

	@SuppressWarnings({ "rawtypes", "unchecked" }) //去除集合的警告
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//多态,
		Collection c = new ArrayList();
		
		//朝集合中添加对象
		c.add(new Person(18,"周健")); // 一定要加 new 进行对象的创建
		c.add(new Person(20,"眉眉")); //
		c.add(new Person(17,"上述")); //
		c.add(new Person(13,"周健")); //
		c.add(1);
		
		//获取元素的个数
		System.out.println(c.size());
		System.out.println(c); //重写Person类中的toString方法前[com.Collection.Person@15db9742, com.Collection.Person@6d06d69c, com.Collection.Person@7852e922, com.Collection.Person@4e25154f]
								//重写Person类中的toString方法后输出[Person [age=18, name=周健], Person [age=20, name=眉眉], Person [age=17, name=上述], Person [age=13, name=周健]]

		//将集合转换为数组遍历输出
		Object[] o = c.toArray();
		for(int i = 0;i<o.length;i++) {
			System.out.println(o[i]);
		}
		
		//判断是否包含,若没有重写Person类中的equals方法则返回false,重写之后返回true
		Person p = new Person(18,"周健");
		System.out.println(c.contains(p));
		
		//删除指定元素
		c.remove(p);
		
		//清空集合
		c.clear();
		System.out.println(c.isEmpty());

	}

}

List集合中特有的方法


		/*
		 	List接口
		 	
		 		List中除了Collection里面的方法以外,内部还有一些方法,通过这些方法,开发者可以更方便的操作List接口的实现类。
		 		
		 		
		 		
		 		add(int index,Eelement)
		 		
		 		get(int index): Returns the element at the specified position in this list。
		 		
		 		
		 		listIterator():Returns a list iterator over the elements in the list(in proper sequence).
		 		
		 		remove(int index) :Removes the element at the specified position in this list(Optional Operation)
		 		
		 		remove(Object o):Removes the first occurrence of the specified element from this listt,if it is present
		 		
		 		set(int index,E element) :Replaces the element at the specified position in this list with the specified element
		 		
		 		toArray()
		 		
		 		iterator()
		 		
		 		listiterator() :也可以进行迭代,在朝集合中添加元素时  将集合转化为此种迭代器
		 
		 */

LinkedList中的方法

LinkedList中特有的方法
		 			
		 			构造方法:
		 					LinkedList()
		 					
		 					LinkedList(Collection<?extends E> c )
		 					
		 			对象方法:
		 			
		 					add(E e)
		 					
		 					add(int index , E element)
		 					
		 					addFirst(E e)
		 					
		 					addLast(E e)
		 					
		 					clear()
		 					
		 					get(int index)
		 					
		 					getFirst() 
		 					
		 					getLast()
		 					
		 					iterator()
		 					
		 					listiterator()
		 					
		 					remove(int index)
		 					
		 					remove(Object o)
		 					
		 					removeFirst()
		 					
		 					removeLast()
		 					
		 					set(int index,E element)
		 					
		 					toArray()
//		LinkedList<Person> l = new LinkedList<>();
//		
//		l.add(new Person("周健",10));
//		l.add(new Person("张三",20));
//		l.add(new Person("李四",20));
//		l.add(new Person("王五",30));
//		l.add(new Person("王五",30));
//		
//		System.out.println(l); //[[周健 :10], [张三 :20], [李四 :20], [王五 :30], [王五 :30]] ;已经重写Person类中的toString方法
//		
//		
//		
//		//任务将l中的不重叠元素添加到l1中
//		ArrayList<Person> l1 = new ArrayList();
//		
//		int num = 0;
//		Object[] o1 = l.toArray();
//		for(int i =0;i<o1.length;i++) {
//			
//			Person p = (Person)o1[i];
//			
//			if(!l1.contains(p)) {
//				l1.add(p);
//				num++;
//			}
//		}
//		System.out.println(l1);
//		System.out.println(num);
		

Vector类简介

Vector是在Jdk1.0版本中就存在的,当时的集合体系还没有现在这么多,在jdk1.2中Vector才实现了Collection接口,不过随着jdk的不断更新,这个类已经逐渐被ArrayList所替代。

泛型

在编写相关代码的时候在eclipse里面总有一些黄色警告,在不适用注解的情况下,使用泛型之后,就不会有这些黄色警告了

通过API可以看到Collection,List,ArrayList,这几个里面都有**<>**,这个就是泛型,里面的E可以是任何引用数据类型(包括自己创建的数据类型 类),使用泛型指明了数据类型之后,这个集合里面只能存储这种数据类型的对象。

泛型的优点
可以统一集合中的数据,提高安全性

		 可以减少强制类型转换

增强for循环

使用增强for循环可以简化数组和Collection集合的遍历,格式:

for( 元素数据类型  变量  :数组或者Collection集合){
		使用变量即可,该变量就是元素
}

集合框架中的三中迭代方式删除数据

(1)普通for循环,可以删除,注意让索引做自减运算

(2)迭代器,可以删除,但是必须用迭代器自身的remove方法,否则会出现并发修改异常

(3)增强for循环不能删除

可变参数和集合数组的互转

可变参数:在定义方法的时候不确定该定义多少个参数,就可以使用可变参数来定义,这样方法的参数会根据调用者来确定。
注意:如果一个方法有可变参数,并且有多个参数,那么,可变参数肯定是最后一个。

格式:

		修饰符 返回值类型  方法名 (数据类型...  变量名){}

HashSet简介

Set里面存储的元素不能重复,没有索引,存取顺序不一致。
这里需要注意:在向HashSet中存放自定义类型对象时,一定要重写hashCode和equals方法

//Set的特点
		//Set里面存储的元素不能重复,没有索引,存取顺序不一致
			//a collection that contains no duplicate elements
		/*
		 	对象方法:
		 			add(E e)
		 			
		 			clear()
		 			
		 			contains(Object o)
		 			
		 			equals(Object o)
		 			
		 			isEmpty()
		 			
		 			iterator()
		 			
		 			size()
		 			
		 			toArray()
/		HashSet<String> hs = new HashSet<>();
//		
//		boolean b1 = hs.add("a");
//		//当向set集合中存储重复元素的时候返回false
//		boolean b2 = hs.add("a");
//		
//		hs.add("b");
//		hs.add("c");
//		hs.add("d");
//		
//		System.out.println(hs); //[a, b, c, d]
//	
//		//可以使用增强for循环或者迭代器进行遍历
//		//只要能用迭代器遍历就能使用增强for循环遍历
//		for(String s:hs) {
//			System.out.println(s);
//		}
		//向HashSet中自定义添加的Person对象,自定义的类需要重写hashCode()方法
//		HashSet<Person> hs = new HashSet<>();
//		hs.add(new Person("周健",10));
//		hs.add(new Person("张三",20));
//		hs.add(new Person("李四",30));
//		hs.add(new Person("王五",40));
//		hs.add(new Person("王五",40));
//		hs.add(new Person("王五",40));
//		
//		for(Person p:hs) {
//			System.out.println(p);
//		}

HashCode方法的作用就是将对象进行分类,然后获取到编号值。

关于重写HashCode方法的一些说明:

任何时候对同一对象多次调用hashCode方法,都必须一致返回同样的整数

如果两个对象通过equals(Object)方法来比较相等,那么这两个对象的hashCode的值必须相等。

LinkedHashSet

通过LinkedHashSet的名字就可以看出,他的底层使用了链表的数据结构,因此LinkedHashSet的特点是读取元素的顺序跟存入元素的顺序是一致的,并且元素不能重复。

	/*
		 * 生成10个1-20之间的整数,并且这些整数是不能重复的
		 */
//		Random r =new Random();
//		HashSet<Integer> hs = new HashSet<Integer>();
//		while(hs.size()<10) {
//			hs.add(r.nextInt(20)+1);
//		}
//		System.out.println(hs);

exe2:将List中的元素去重

//		ArrayList<String> list = new ArrayList<>();
//		list.add("a");
//		list.add("a");
//		list.add("b");
//		list.add("b");
//		list.add("c");
//		list.add("d");
//		
//		LinkedHashSet<String> lhs = new LinkedHashSet<>();
//		//将list集合中的所有元素添加到lhs
//		lhs.addAll(list);
//		
//		//将list中清空
//		list.clear();
//		//把去除重复元素之后的元素添加到list中
//		list.addAll(lhs);
//		//增强for循环
//		for(String s:list) {
//			System.out.println(s);
//		}

TreeSet简介

TreeSet的特点是可以对存进去的元素进行排序。

		//存储Intege类型
//		TreeSet<Integer> ts = new TreeSet<>();
//		
//		ts.add(1);
//		ts.add(7);
//		ts.add(1);
//		ts.add(4);
//		ts.add(2);
//		ts.add(6);
//		System.out.println(ts); //[1, 2, 4, 6, 7]
		
		
		/*
		 	使用TreeSet存储自定义类型需要使用到 Interface Comparable<T> 接口 重写其中的 CompareTo()方法
		 	
		 	This interface implements a total ordering on the objects of each class that implements it.
		 	This ordering is referened to as the class's natural ordering,and the class's compareTo method is referred to as its natural comparsion method
		 	
		 	构造方法:
		 	TreeSet()  //Constructs a new,empty tree set,sorted according to the natural ordering of its elements
		 	
		 	TreeSet(Comparator<?super E> comparator)  //Constructs a new ,empty tree set ,sorted according to the specified comparator
		 
		 
		 
		 
		 */
		
		//使用TreeSet存储自定义类型对象
//		TreeSet<Person> st = new TreeSet<>();
		//直接这样添加,报错String中无法对中文进行排序,因为里面的ComprareTo计算的两个Char类型的差
		//需要重写方法 CompareTo;AbstractMethodError: Person.compareTo(Ljava/lang/Object;)I
		//需要参考CompareTo方法 
		/*  compareTo方法的返回值:
		 * 				TreeSet使用了二叉树的数据结构,负数放到左边,正数放到右边:
		 * 					当compare方法返回0的时候,系统会认为二者一致,所以不会向集合中添加元素
		 * 					当compareTo方法返回正数的时候,系统将元素存储到右边,所以集合存取顺序一致
		 * 					当compareTo方法返回负数的时候,系统将元素存储到左边,所以集合会倒序存储
		 * 
		 */

Map简介

在这里插入图片描述
map中的元素是以 键 - 值的方式 存在的,通过键可以获取到值,键是不能重复的,跟地图比较像,通过一个坐标就可以找到具体的值。


					分类: 
						HashMap
						
						LinkedHashMap:存取顺序一致’
						
						
						TreeMap:可以对存储的元素进行排序
						
		
//		Map<Integer, String> map = new HashMap<>();
//		
//		map.put(1001, "成龙");
//		map.put(1002, "周润发");
//		map.put(1003, "周星驰");
//		
//		//判断是否包含键值
//		System.out.println(map.containsKey(1001)); 
//		
//		//判断是否包含传入值
//		System.out.println(map.containsValue("成龙"));
//		
//		//计算MAP的长度
//		System.out.println(map.size()); //3
//		
//		//Returns a Collection view of the value contained in this map
//		Collection<String> c = map.values();
//		System.out.println(c);//[成龙, 周润发, 周星驰]
		
		
		//Map的遍历
		
		//方法1:Map中的KeySet返回的是一个包含所有键的Set类型的对象,通过键获取值
		//Set<Integer> set = map.keySet();
		//使用增强for循环
//		for(Integer i :set) {
//			System.out.println("键为:"+i+" "+"值为:" +map.get(i));
//		}
		
		//遍历set获取
//		Iterator<Integer> itr = set.iterator();
//		while(itr.hasNext()) {
//			Integer key = (Integer)itr.next();
//			System.out.println("键为:"+itr.next()+" "+"值为:" +map.get(key));
//		}
		
		
		
		//方式2:Map中的键和值封装成Entry对象,并存储在Set集合中,通过entrySet() 可以获取到这个Set集合
//		Set<Map.Entry<Integer, String>>  set= map.entrySet();
//		
//		Iterator<Map.Entry<Integer, String>> itr = set.iterator();
//		
//		while(itr.hasNext()) {
//			
//			//获取每一个Entry对象
//			Entry<Integer,String> en = itr.next();
//			
//			//根据键值对对象获取键
//			Integer key = en.getKey();
//			
//			//根据键值对对象获取值
//			String value = en.getValue();
//			
//			System.out.println("键"+key+"值"+value);
//		
//		}
		
		
		
//		for(Map.Entry s:set) {
//			System.out.println("键为:"+s.getKey()+"  "+"值为:"+s.getValue());
//		}
		

Collections工具类简介

就像数组中的Arrays工具类一样,在集合里面也有跟Arrays类似的工具类 Collections。

		ArrayList<Integer> list = new ArrayList<>();
		list.add(1);
		list.add(10);
		list.add(3);
		list.add(7);
		list.add(6);
		
		//根据默认排序结果获取集合的最大值
		System.out.println(Collections.max(list));
		
		//翻转集合
		Collections.reverse(list);
		System.out.println(list);

		//随机置换,可以用来洗牌
		Collections.shuffle(list);
		
		//排序
		Collections.sort(list);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值