List集合与Set集合的区别
List
和Set
都是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
集合的常用实现类有ArrayList
和LinkedList
,其中,ArrayList
是使用数组结构来存储的,数组结构要求数据在内存中必须是连续的,存在查询效率高,但修改效率低的问题;而LinkedList
是使用链表结构来存储的,存在查询效率低,但修改效率高的问题!
Set
集合的常用实现类有HashSet
,其数据是完全散列的,而LinkedHashSet
也是使用链表结构来存储数据的!