List集合与Set集合的区别

List集合与Set集合的区别

ListSet都是Collection集合的子级接口!

List序列的,主要表现为其中的各元素在内存中是存在顺序规则的;另外,List中的元素是可以重复的,即可以向同一个List集合中反复添加相同的数据;

Set散列的,主要表现为其中的各元素在内存中的位置是散列的,如果使用不同的实现类来存储数据,最终在显示Set集合中的所有元素时,显示结果可能是无序的(HashSet),或根据排序规则进行排列的(TreeSet),或根据添加顺序进行排列的(LinkedHashSet);另外,Set中的元素是不可重复的,即不可以向同一个Set集合中反复添加相同的数据,关于“是否相同”,取决于equals()的对比结果与hashCode()值的对比,如果2个对象的equals()对比为true,并且hashCode()值相等,则视为“相同”!

演示代码:

package cn.tedu.spring;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;

public class CollectionDemo {

	public static void main(String[] args) {
		Set<String> strings = new LinkedHashSet<String>();
		strings.add("str-1");
		strings.add("str-5");
		strings.add("str-3");
		strings.add("str-2");
		strings.add("str-2");
		strings.add("str-2");
		strings.add("str-2");
		strings.add("str-2");
		strings.add("str-4");
		System.out.println(strings);
		
		Set<Student> students = new HashSet<Student>();
		students.add(new Student("Mike", 18));
		students.add(new Student("Frank", 20));
		students.add(new Student("Frank", 20));
		students.add(new Student("Frank", 25));
		students.add(new Student("Joe", 25));
		for (Student student : students) {
			System.out.println(student);
		}
	}

}

class Student {
	public String name;
	public int age;
	
	public Student(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}
}

题外话:集合的实现类的存储结构

List集合的常用实现类有ArrayListLinkedList,其中,ArrayList是使用数组结构来存储的,数组结构要求数据在内存中必须是连续的,存在查询效率高,但修改效率低的问题;而LinkedList是使用链表结构来存储的,存在查询效率低,但修改效率高的问题!

Set集合的常用实现类有HashSet,其数据是完全散列的,而LinkedHashSet也是使用链表结构来存储数据的!

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值