Java中Collection集合

本文深入探讨了Java集合框架的体系结构,对比了数组与集合的特点,详细解析了List、Set及Map的不同实现方式,并通过示例代码展示了集合的基本使用、函数判断及迭代输出等功能。

集合体系图

集合和数组的比较

数组:存储同一种数据类型

 特点:

       1.只能存储一种数据类型

       2.一旦初始化,长度固定

       3.数组元素的内存地址是连续的

       4.Object类型的数组可以存储任意类型的元素

 需求:收集同学的兴趣爱好

 集合:存储对象数据的集合容器

 优势:

1. 集合可以存储任意类型的对象信息,数组只能存储同一类型对象信息(Object除外)

2.集合的长度是任意变化的,数组长度是固定的

 

集合的体系结构

--|Collection:单列集合的根接口,表示一组对象

----|List 实现List接口的集合类,特点:有序可以重复

------|ArrayList 维护Object数组实现的,特点:查询快,增删慢

------|LinkedList 底层使用链表数据结构实现的,特点:查询慢,增删快

------|Vector 底部维护Object数组,实现和ArrayList一样,但是Vector是线程安全,效率低

----|Set 实现Set接口的集合类,特点:无序,不可重复

------|HashSet 底层是使用了哈希表来支持的,特点: 存取速度快.

--------|特点:hashSet的实现原理:

           往Haset添加元素的时候,HashSet会先调用元素的hashCode方法得到元素的哈希值 ,

          然后通过元素的哈希值经过移位等运算,就可以算出该元素在哈希表中的存储位置。

          情况1:如果算出元素存储的位置目前没有任何元素存储,那么该元素可以直接存储到该位置上。

 情况2: 如果算出该元素的存储位置目前已经存在有其他的元素了,那么会调用该元素的equals方法与该位置的元素再比较一次,如果equals返回的是true,那么该元素与这个位置上的元素就视为重复元素,不允许添加,如果equals方法返回的是false,那么该元素运行添加。

------|TreeSet

--------|如果元素具备自然顺序的特性,那么就按照元素自然顺序的特性进行排序

双例集合体系

双列集合:

   Map:实现Map接口的集合类,具备的特点:存储的数据都是以键值对的方式,键不可以重复,值可重复

   --|HashMap

底层使用hashCode表来实现向HashMap中添加元素的时候,首先调用键的hashCode方法得到元素的哈希码的值,经过运算,得到该元素在哈希表中的位置;

   1.如果该位置没有存储元素,则元素之间添加到哈希表中

   2.如果该位置有其他的元素,会调用元素的equals方法,如果返回false,该元素被储存,返回true,该元素重复不能存储

   --|TreeMap

TreeMap:基于二叉树的数据结构实现的,会对具备自然特性的键进行排序存储

1.元素的键具备自然特性,直接排序存储

2.不具备自然特性,实现Comparable接口,在ComparaTo中定义排序规则

3.不具备自然特性,没有实现Comparable接口,在创建TreeMap对象的时候传入比较器

   --|HashTable

collection集合

基本使用

package com.cloud.day1;
import java.util.ArrayList;
import java.util.Collection;
/*
--|Collection:单列集合的根接口,表示一组对象
----|List 实现List接口的集合类,特点:有序可以重复
----|Set  实现Set接口的集合类,特点:无序,不可重复
Collection中的方法
	添加
	add(E e) 
	addAll(Collection<? extends E> c) 
	
	删除
	clear() 
	remove(Object o)
	removeAll(Collection<?> c)
	retainAll(Collection<?> c)
	
	查看
	size() 
	
	判断
	contains(Object o) 
	containsAll(Collection<?> c) 
	equals(Object o) 
	isEmpty() 
	
	迭代
	iterator() 
	toArray()
 */
 
public class Demo1 {
	public static void main(String[] args) {
		Collection test=new ArrayList();
		test.add("SHsH");
		test.add("sjf");
		test.add(1);
		Collection c=new ArrayList();
		c.add("Spring");
		c.add(1);
		c.addAll(test);
		System.out.println("添加成功返回值?"+c.add("Summer"));
		//c.clear();
		c.remove("sjf");
		//c.removeAll(test);//删除两个集合的交集
		c.retainAll(test);//保留c集合和test集合的交集元素,其余删除
		
		System.out.println(c);
	}
}	

集合中的函数判断

package com.cloud.day1;
import java.util.ArrayList;
import java.util.Collection;
public class Demo2 {
	public static void main(String[] args) {
		Collection<Person> all=new ArrayList<Person>();
		all.add(new Person(1,"Spring1"));
		all.add(new Person(2,"Spring2"));
		all.add(new Person(3,"Spring3"));
		all.add(new Person(4,"Spring4"));
		System.out.println("判断包含:"+all.contains(new Person(1,"Spring1")));
		System.out.println(all);
	}
}
class Person{
	private int id;
	private String name;
	public Person(int id,String name){
		this.id=id;
		this.name=name;
	}
	public String toString() {
		return "编号:"+this.id+";姓名:"+this.name;
	}
	/**
	 * 重写比较方法
	 */
	public boolean equals(Object obj) {
		Person p=(Person) obj;//向下转型
		return this.id == p.id;
	}
	/**
	 * java的规范,重写equals方法就会重写hashCode方法
	 */
	public int hashCode() {
		return this.id;
	}
}

迭代输出集合元素

package com.cloud.day1;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Demo3 {
	public static void main(String[] args) {
		Collection c=new ArrayList();
		c.add("Spring1");
		c.add("Spring2");
		c.add("Spring3");
		/*迭代器输出元素
		Iterator it=c.iterator();
		while(it.hasNext()){
			System.out.println(it.next());
		}
		
		
		for(Iterator it=c.iterator();it.hasNext();){
			System.out.println("["+it.next()+"]");
		}
		*/
		//remove:方法删除最后一次返回的元素
//		Iterator it=c.iterator();//这时候获取一个迭代器还没有获取元素
//		it.next();
//		it.remove();//删除Spring1
		
//		Iterator it=c.iterator();//这时候获取一个迭代器还没有获取元素
//		it.next();
//		it.next();
//		it.remove();//删除Spring2
		
		//删除全部
		Iterator it=c.iterator();//这时候获取一个迭代器还没有获取元素
		while (it.hasNext()){
			it.next();
			it.remove();
		}
		System.out.println(c);
	}
}

模拟登录注册案例

package com.cloud.day1;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Scanner;
public class Demo4 {
	/**
	 * @param模拟注册登录的案例
	 * 1.如果用户名和密码已经存在,则注册失败
	 * 2.则注册成功
	 */
	public static void main(String[] args) {
		Scanner scanner=new Scanner(System.in);
		Collection users=new ArrayList();
		while(true){
			System.out.println("请选择功能:A.注册  B.登录");
			String option=scanner.next();
			if("a".equalsIgnoreCase(option)){
				System.out.println("你选择了注册功能");
				User user=null;
				while (true){
					System.out.println("请输入账号...");
					int id=scanner.nextInt();
					user=new User(id, null);
					if(users.contains(user)){
						System.out.println("该用户已经存在,重新输入...");
					}
					else{
						break;
					}
				}
				System.out.println("请输入密码...");
				String password=scanner.next();
				user.setPassword(password);
				//存入集合中
				users.add(user);
				System.out.println("注册成功");
				System.out.println("注册人员信息"+users);
				/*
				System.out.println("你选择注册功能");
				while(true){
					System.out.println("请输入账号...");
					int id=scanner.nextInt();
					//遍历集合是否存在该账号
					Iterator it=users.iterator();
					while(it.hasNext()){
						User user=(User) it.next();
						if(user.id==id){
							System.out.println("该账号已经被注册,重新输入...");
							break;
						}
					}
				}
				*/
			}
			else if("b".equalsIgnoreCase(option)){
				System.out.println("你选择登录功能");
				System.out.println("请输入账号...");
				int id=scanner.nextInt();
				System.out.println("请输入密码...");
				String password=scanner.next();
				//遍历集合元素查看用户信息
				boolean isLogin=false;
				Iterator it=users.iterator();
				while(it.hasNext()){
					User user=(User) it.next();
					if(user.id==id && user.password.equals(password)){
						isLogin=true;
					}
				}
				if(isLogin){
					System.out.println("欢迎进入...");
				}
				else{
					System.out.println("用户名或者密码错误");
				}
			}
			else{
				System.out.println("你的选择错误,重新输入");
			}
		}
	}

}
class User{
	int id;
	String password;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public User(int id,String password){
		this.id=id;
		this.password=password;
	}
	@Override
	public boolean equals(Object obj) {
		User user=(User) obj;
		return this.id==user.id;
	}
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "(账号:"+this.id+",密码:"+this.password+")";
	}
}

Collections集合的工具类

package com.cloud.collection;

 

import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

/*

笔试题:CollectionCollections区别

Collection是单例集合的根接口

Collections是操作集合对象的工具类

 */

class Person{

   String name;

   int age;

   public Person(String name,int age){

      this.name=name;

      this.age=age;

   }

   @Override

   public String toString() {

      return "[姓名:"+this.name+";年龄:"+this.age+"]";

   }

}

//自定义一个比较器

class AgeComparator implements Comparator<Person>{

   @Override

   public int compare(Person o1, Person o2) {

      return o1.age - o2.age;

   }

}

public class Demo1 {

   public static void main(String[] args) {

      ArrayList<Integer> arr = new ArrayList<Integer>();

      arr.add(6);

      arr.add(4);

      arr.add(2);

      Collections.sort(arr);

      //二分查找,要先排序

      System.out.println("元素索引的位置:"+Collections.binarySearch(arr, 2));

      System.out.println("max="+Collections.max(arr));

      System.out.println("min="+Collections.min(arr));

      //数组翻转

      Collections.reverse(arr);

      System.out.println(arr);

      ArrayList<Person> arr1 = new ArrayList<Person>();

      arr1.add(new Person("a",5));

      arr1.add(new Person("c",3));

      arr1.add(new Person("b",6));

      AgeComparator act = new AgeComparator();

      Collections.sort(arr1, act);

      System.out.println(Collections.binarySearch(arr1, new Person("a",5),act));

      System.out.println(arr1);

   }

}

<think>嗯,用户问的是Java中的Collection单列集合。首先,我需要回忆一下Java集合框架的基础知识。记得Java集合框架主要分为Collection和Map两大类,而Collection是单列集合,Map是双列的键值对。用户可能想了解Collection的体系结构、常用接口和实现类,以及它们的使用场景。 首先,应该从Collection的顶层接口开始介绍,说明它继承了Iterable接口,所以所有Collection的实现类都支持迭代。然后,Collection分为List、Set和Queue三个子接口,每个子接口有不同的特性。 List部分,需要提到有序、可重复的特点,常用的实现类有ArrayList、LinkedList和Vector。要比较它们的底层实现,比如ArrayList基于数组,查询快,增删慢;LinkedList基于链表,增删快,查询慢;Vector是线程安全的,但性能较差,现在可能不常用了。 接下来是Set,强调元素唯一且无序。常用的实现类有HashSet、LinkedHashSet和TreeSet。HashSet基于哈希表,LinkedHashSet维护插入顺序,TreeSet可以排序。可能需要提到TreeSet是基于红黑树实现的,自然排序或者通过Comparator定制排序。 然后是Queue,队列,常用的有LinkedList、PriorityQueue,还有线程安全的ArrayBlockingQueue等。需要说明队列的先进先出特性,以及优先级队列的特殊之处。 用户可能还想知道如何选择不同的集合类,比如需要快速访问用ArrayList,需要频繁插入删除用LinkedList,需要唯一性用HashSet,需要排序用TreeSet,需要线程安全的话考虑使用Collections工具类或者并发包下的类。 另外,可能需要提到集合的遍历方式,比如for-each循环、迭代器、Java8的Stream API等。还要注意集合的线程安全问题,比如ArrayList不是线程安全的,多线程环境下应该用CopyOnWriteArrayList或者同步包装类。 用户可能的疑问还包括如何正确实现对象的equals和hashCode方法,特别是当使用HashSet或HashMap的时候。这也是确保集合正确行为的关键点。 最后,总结一下Collection的层次结构,以及各个实现类的适用场景,帮助用户在实际开发中做出合适的选择。可能还需要提醒一些常见错误,比如在遍历集合时修改导致的ConcurrentModificationException异常,以及如何避免。</think>Java中的Collection单列集合是存储一组对象的容器,属于Java集合框架的核心部分。以下从体系结构、常用接口和实现类进行分步解析: 1. **Collection顶层接口** - 继承自`Iterable`接口,支持迭代遍历 - 核心方法: ```java boolean add(E e); // 添加元素 boolean remove(Object o); // 删除元素 int size(); // 元素数量 boolean contains(Object o); // 判断包含 Iterator<E> iterator(); // 获取迭代器 ``` 2. **三大子接口** $$\begin{array}{|c|c|c|} \hline \text{接口} & \text{特点} & \text{常用实现类} \\ \hline \text{List} & \text{有序、可重复} & ArrayList, LinkedList, Vector \\ \text{Set} & \text{无序、唯一} & HashSet, LinkedHashSet, TreeSet \\ \text{Queue} & \text{队列结构} & LinkedList, PriorityQueue \\ \hline \end{array}$$ 3. **List接口详解** - **ArrayList**(数组实现): - 查询效率高($O(1)$随机访问) - 增删效率较低(需要移动元素) - **LinkedList**(双向链表实现): - 增删效率高($O(1)$头尾操作) - 查询效率低($O(n)$顺序访问) - **Vector**(线程安全数组): - 已被`Collections.synchronizedList()`取代 4. **Set接口详解** - **HashSet**(哈希表实现): - 基于`HashMap`实现 - 要求元素正确实现`hashCode()`和`equals()` - **LinkedHashSet**: - 维护插入顺序的HashSet - **TreeSet**(红黑树实现): - 支持自然排序或`Comparator`定制排序 - 元素必须实现`Comparable`接口 5. **Queue接口特性** - **PriorityQueue**: - 基于堆结构实现优先级队列 - 元素按自然顺序或Comparator排序 - **LinkedList**: - 可同时作为List和Deque使用 6. **使用示例** ```java // ArrayList示例 List<String> list = new ArrayList<>(); list.add("Java"); list.add("Python"); System.out.println(list.get(0)); // 输出:Java // HashSet示例 Set<Integer> set = new HashSet<>(); set.add(1); set.add(1); // 重复元素不会添加 System.out.println(set.size()); // 输出:1 // TreeSet排序示例 Set<String> sortedSet = new TreeSet<>(); sortedSet.add("Banana"); sortedSet.add("Apple"); System.out.println(sortedSet); // 输出:[Apple, Banana] ``` 7. **选择策略** - 需要快速随机访问 → ArrayList - 频繁插入删除 → LinkedList - 元素唯一性 → HashSet - 需要排序 → TreeSet - 线程安全需求 → 使用`Collections.synchronizedCollection()`包装或改用并发集合 8. **遍历方式** - 传统for循环(仅List) - 增强for循环 - Iterator迭代器 - Java8 Stream API: ```java list.stream().forEach(System.out::println); ``` 理解Collection体系需要掌握: 1. 各实现类的底层数据结构 2. 时间空间复杂度差异 3. 特定场景下的最佳实践 4. 线程安全问题的处理方式 建议通过实际编码练习加深理解,特别注意不同集合对元素相等性的判断机制,以及排序集合对元素可比性的要求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值