Java学习------集合入门
集合分类
Java中的集合按大类可分为Collection和Map;
1、Collection是单列集合;Map是双列集合;
2、Collection分为list和set;其中Set要求元素唯一;Map中键需要唯一,与键对应的值不需要唯一;
3、Collection的数据结构针对元素,Map的数据结构针对键值对。
Collection
List
List的特点:存取有序,存在索引(下标),可以根据索引(下标)进行存取,元素可以重复。
List又可分为 ArrayList,LinkedList,Vector (已过时,不进行叙述)。
ArrayList
ArrayList底层用数组实现,查询快,增删慢,线程不安全,效率高。
public class Test {
// 使用ArrayList进行添加和遍历
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("元素1");
list.add("元素2");
list.add("元素3");
// 第一种遍历方式,使用迭代器
Iterator<String> it = list.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
// 第二种遍历方式,使用foreach
for (String str : list){
System.out.println(str);
}
// 第三种遍历方式,使用数组
String[] str = new String[list.size()];
list.toArray(str);
for(int i = 0; i < str.length; i++){
System.out.println(str[i]);
}
}
}
LinkedList
LinkedList是基于链表结构实现,查询慢,增删快,线程不安全,效率高,可对头尾的元素进行操作。
使用LinkedList来实现栈和队列,栈是先进后出,队列是先进先出。
/**
* 利用LinkedList来模拟栈
* 栈的特点:先进后出
*
*/
public class MyStack {
private LinkedList<String> linkList = new LinkedList<String>();
// 压栈
public void push(String str){
linkList.addFirst(str);
}
// 出栈
public String pop(){
return linkList.removeFirst();
}
// 查看
public String peek(){
return linkList.peek();
}
// 判断是否为空
public boolean isEmpty(){
return linkList.isEmpty();
}
}
public class Test {
public static void main(String[] args) {
// 测试栈
StackTest stack = new StackTest();
stack.push("我是第1个进去的");
stack.push("我是第2个进去的");
stack.push("我是第3个进去的");
stack.push("我是第4个进去的");
stack.push("我是第5个进去的");
// 取出
while (!stack.isEmpty()){
String pop = stack.pop();
System.out.println(pop);
}
// 打印结果
/*我是第5个进去的
我是第4个进去的
我是第3个进去的
我是第2个进去的
我是第1个进去的*/
}
}
/**
* 利用linkedList来实现队列
* 队列: 先进先出
*
*/
public class QueueTest {
private LinkedList<String> link = new LinkedList<String>();
// 放入
public void put(String str){
link.addFirst(str);
}
// 获取
public String get(){
return link.removeLast();
}
// 判断是否为空
public boolean isEmpty(){
return link.isEmpty();
}
}
public class Test {
public static void main(String[] args) {
// 测试队列
QueueTest queue = new QueueTest();
queue.put("我是第1个进入队列的");
queue.put("我是第2个进入队列的");
queue.put("我是第3个进入队列的");
queue.put("我是第4个进入队列的");
// 遍历队列
while (!queue.isEmpty()){
String str = queue.get();
System.out.println(str);
}
// 打印结果
/*我是第1个进入队列的
我是第2个进入队列的
我是第3个进入队列的
我是第4个进入队列的*/
}
}
Set
Set的特点:元素不重复,存取无序,无索引(下标)。
Set又可分为:HashSet、LinkedHashSet、TreeSet。
HashSet存储字符串:
package 好好学java;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Test {
public static void main(String[] args) {
// 利用HashSet来存取
Set<String> set = new HashSet<String>();
set.add("我的天");
set.add("我是重复的");
set.add("我是重复的");
set.add("welcome");
// 遍历 第一种方式 迭代器
Iterator<String> it = set.iterator();
while(it.hasNext()){
String str = it.next();
System.out.println(str);
}
//遍历 第二种方式 foreach
for (String str : set){
System.out.println(str);
}
// 打印结果,重复的已经去掉了
/*我的天
welcome
我是重复的
--------------
我的天
welcome
我是重复的*/
}
哈希表是怎么来保证元素的唯一性的?
哈希表是通过hashCode和equals方法来共同保证的。
根据存储的元素计算出hashCode值,然后根据计算得出的hashCode值和数组的长度进行计算出存储的下标;如果下标的位置无元素,那么直接存储;如果有元素,那么使用要存入的元素和该元素进行equals方法,如果结果为真,则已经有相同的元素了,所以直接不存;如果结果假,那么进行存储,以链表的形式存储。
HashSet存储自定义对象
public class Person {
// 属性
private String name;
private int age;
// 构造方法
public Person() {
super();
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
// 要让哈希表存储不重复的元素,就必须重写hasCode和equals方法
@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;
Person other = (Person) 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 "Person [name=" + name + ", age=" + age + "]";
}
// getter & setter
...
}
public class Test {
public static void main(String[] args) {
// 利用HashSet来存取自定义对象 Person
Set<Person> set = new HashSet<Person>();
set.add(new Person("张三", 12));
set.add(new Person("李四", 13));
set.add(new Person("王五", 22));
set.add(new Person("张三", 12));
// 遍历
for (Person p : set){
System.out.println(p);
}
// 结果:向集合中存储两个张三对象,但是集合中就成功存储了一个
/*Person [name=王五, age=22]
Person [name=李四, age=13]
Person [name=张三, age=12]*/
}
}
在向HashSet集合中存储自定义对象时,为了保证set集合的唯一性,那么必须重写hashCode和equals方法。
LinkedHashSet
LinkedHashSet是基于链表和哈希表共同实现的,存取有序,元素唯一。
public class Test {
public static void main(String[] args) {
// 利用LinkedHashSet来存取自定义对象 Person
LinkedHashSet<Person> set = new LinkedHashSet<Person>();
set.add(new Person("张三", 12));
set.add(new Person("李四", 13));
set.add(new Person("王五", 22));
set.add(new Person("张三", 12));
// 遍历
for (Person p : set){
System.out.println(p);
}
// 结果:向集合中存储两个张三对象,但是集合中就成功存储了一个,
// 并且存进的顺序,和取出来的顺序是一致的
/*Person [name=张三, age=12]
Person [name=李四, age=13]
Person [name=王五, age=22]*/
}
}
TreeSet:是基于二叉树实现的,存取无序,元素唯一,可以进行排序(在添加时进行排序)。
TreeSet存储字符串
public class Test {
public static void main(String[] args) {
TreeSet<String> treeSet = new TreeSet<String>();
treeSet.add("abc");
treeSet.add("zbc");
treeSet.add("cbc");
treeSet.add("xbc");
for (String str : treeSet){
System.out.println(str);
}
// 结果:取出来的结果是经过排序的
/*
abc
cbc
xbc
zbc*/
}
}
TreeSet保证元素的唯一性是有两种方式:
1、自定义对象实现Comparable接口,重写comparaTo方法,该方法返回0表示相等,小于0表示准备存入的元素比被比较的元素小,否则大于0;
2、在创建TreeSet的时候向构造器中传入比较器Comparator接口实现类对象,实现Comparator接口重写compara方法。
Map
Map是一个双列集合,储存的是键值对,键具有唯一性,值可以重复,键值是一一对应的,
一个键只能对应一个值。
Map的特点:是存取无序,键不可重复
Map可分为HashMap,LinkedHashMap和TreeMap。
HashMap
HashMap是基于哈希表结构实现的,存取无序,存储自定义对象作为键时,必须重写hasCode和equals方法。
HashMap用自定义对象作为键
public class Test {
public static void main(String[] args) {
// 利用HashMap存储,自定义对象Person作为键
// 为了保证键的唯一性,必须重写hashCode和equals方法
HashMap<Person,String> map = new HashMap<Person,String>();
map.put(new Person("张三", 12), "JAVA");
map.put(new Person("李四", 13), "IOS");
map.put(new Person("小花", 22), "JS");
map.put(new Person("小黑", 32), "PHP");
map.put(new Person("张三", 12), "C++");
Set<Entry<Person, String>> entrySet = map.entrySet();
//使用迭代器进行遍历
Iterator<Entry<Person, String>> it = entrySet.iterator();
while (it.hasNext()){
Entry<Person, String> entry = it.next();
System.out.println(entry.getKey() + "---" + entry.getValue());
}
// 结果:存入的时候添加了两个张三,如果Map中键相同的时候,当后面的值会覆盖掉前面的值
/*
Person [name=李四, age=13]---IOS
Person [name=张三, age=12]---C++
Person [name=小黑, age=32]---PHP
Person [name=小花, age=22]---JS
*/
}
}
LinkedHashMap
LinkedHashMap是基于链表和哈希表结构实现的,存储有序,键不重复,存储自定义对象作为键时,必须重写hasCode和equals方法。
LinkedHashMap用自定义对象作为键,注意存储的顺序和遍历出来的顺序是一致的。
public class Test {
public static void main(String[] args) {
// 利用LinkedHashMap存储,自定义对象Person作为键
// 为了保证键的唯一性,必须重写hashCode和equals方法
LinkedHashMap<Person,String> map = new LinkedHashMap<Person,String>();
map.put(new Person("张三", 12), "JAVA");
map.put(new Person("李四", 13), "IOS");
map.put(new Person("小花", 22), "JS");
map.put(new Person("小黑", 32), "PHP");
map.put(new Person("张三", 12), "C++");
// foreach遍历
for (Entry<Person,String> entry : map.entrySet()){
System.out.println(entry.getKey()+"==="+entry.getValue());
}
// 结果:存入的时候添加了两个张三,如果Map中键相同的时候,当后面的值会覆盖掉前面的值
// 注意:LinkedHashMap的特点就是存取有序,取出来的顺序就是和存入的顺序保持一致
/*
Person [name=张三, age=12]===C++
Person [name=李四, age=13]===IOS
Person [name=小花, age=22]===JS
Person [name=小黑, age=32]===PHP
*/
}
}
TreeMap
TreeMap是基于二叉树结构实现的,存储的数据都需要排序,存储自定义对象时,需要对象所属的类实现Comparable接口或者给TreeMap集合传递一个Comparator接口对象。
TreeMap用自定义对象作为键
public class Test {
public static void main(String[] args) {
// 利用TreeMap存储,自定义对象Person作为键
// 自定义对象实现Comparable接口或者传入Comparator比较器
TreeMap<Person,String> map = new TreeMap<Person,String>(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
if (o1 == o2){
return 0;
}
int result = o1.getAge() - o2.getAge();
if (result == 0){
return o1.getName().compareTo(o2.getName());
}
return result;
}
});
map.put(new Person("张三", 12), "JAVA");
map.put(new Person("李四", 50), "IOS");
map.put(new Person("小花", 32), "JS");
map.put(new Person("小黑", 32), "PHP");
map.put(new Person("张三", 12), "C++");
// foreach遍历
for (Entry<Person,String> entry : map.entrySet()){
System.out.println(entry.getKey()+"==="+entry.getValue());
}
// 结果:存入的时候添加了两个张三,如果Map中键相同的时候,当后面的值会覆盖掉前面的值
// 注意:TreeMap 取出来的顺序是经过排序的,是根据compara方法排序的
/*
Person [name=张三, age=12]===C++
Person [name=小花, age=32]===JS
Person [name=小黑, age=32]===PHP
Person [name=李四, age=50]===IOS
*/
}
}
原文地址:https://juejin.im/post/5ad82dbef265da503825b240#heading-5