Java常用List、Map集合工具类

x33g5p2x  于2021-08-07 转载在 Java  
字(6.8k)|赞(0)|评价(0)|浏览(378)

一、集合概念和适用场景

  • Java中的集合是工具类,可以存储任意数量的具有共同属性的对象。
  • 集合适用于数据动态变换, 数组适用于固定大小数据
  • 无法预测存储数据的数量
  • 同时存储具有一对一关系的数据
  • 需要进行数据的增删
  • 数据重复问题

二、集合框架的体系结构

三、List 列表

  • List是元素有序并且可以重复的集合,称为序列
  • List可以精确的控制每个元素的插入位置,或删除某个元素的位置
  • List的两个主要实现类是ArrayList和LinkedList

ArrayList:

  • ArrayList底层是由数组实现的
  • 动态增长,以满足应用程序的需求
  • 在列表尾部插入或删除数据非常有效
  • 更适合查找和更新元素
  • ArrayList中的元素可以为空
  • 默认长度十

 

案例:添加字符串

package com.csdn.set;

import java.util.ArrayList;
import java.util.List;

public class ListDemo1 {

	public static void main(String[] args) {
		// 用ArrayList存储编程语言的名称,并输出
		List list = new ArrayList();
		list.add("Java");
		list.add("C");
		list.add("C++");
		list.add("Go");
		list.add("Java");
		list.add("swift");
		//输出列表中元素的个数
		System.out.println("列表中元素的个数为: " + list.size());
		
		//遍历输出所有的编程语言
		System.out.println("********************************");
		for (int i = 0; i < list.size(); i++) {
			System.out.print(list.get(i) + ",");
		}
		
		//移除列表中的C++
		list.remove(2); //list.remove("C++");
		
		//遍历输出所有的编程语言
		System.out.println("********************************");
		for (int i = 0; i < list.size(); i++) {
			System.out.print(list.get(i) + ",");
		}
	}
}

案例:添加对象

Notice.java

package com.csdn.set;

import java.util.Date;

public class Notice {
	private int id;
	private String title;
	private String creator;
	private Date createTime;
	
	public Notice() {
		
	}
	
	public Notice(int id, String title, String creator, Date createTime) {
		super();
		this.id = id;
		this.title = title;
		this.creator = creator;
		this.createTime = createTime;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getCreator() {
		return creator;
	}

	public void setCreator(String creator) {
		this.creator = creator;
	}

	public Date getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}	
}

NoticeTest.java

package com.csdn.set;

import java.util.ArrayList;
import java.util.Date;

public class NoticeTest {

	public static void main(String[] args) {
		// 创建对象
		Notice notice1 = new Notice(1, "欢迎来到csdn", "管理员", new Date());
		Notice notice2 = new Notice(2, "请同学们按时完成作业", "老师", new Date());
		Notice notice3 = new Notice(3, "考勤通知", "老师", new Date());
		
		// 添加公告
		ArrayList noticeList = new ArrayList();
		noticeList.add(notice1);
		noticeList.add(notice2);
		noticeList.add(notice3);
		
		// 显示公告
		System.out.println("公告的内容为: ");
		for (int i = 0; i < noticeList.size(); i++) {
			System.out.println(i + 1 + ":" + ((Notice)(noticeList.get(i))).getTitle());
		}
	}
}

四、Set 集合

  • Set是元素无序并且不可以重复的集合,别称为集。
  • Set是接口,不能创建对象

HashSet

  • HashSet是Set的一个重要实现类, 称为哈希集
  • HashSet中的元素无序并且不可以重复
  • HashSet中只允许一个null元素
  • 具有良好的存取和查找性能
  • HashSet删除元素的时候通过遍历的方式只能删除一个后break, 如果需要删除多个需要创建一个新的集合,将满足条件的数据添加到新的集合中,然后通过removeAll删除满足条件的集合

Iterator(迭代器)

  • Iterator接口可以以统一的方式对各种集合元素进行遍历
  • hasNext()方法检测集合中是否还有下一个元素
  • next()方法返回集合的下一个元素

案例(字符串):将英文单词添加到HashSet中

package com.csdn.set;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class WordDemo {

	public static void main(String[] args) {
		// 将英文单词添加到HashSet中
		Set set = new HashSet();
		set.add("blue");
		set.add("red");
		set.add("white");
		set.add("black");
		set.add("green");
		
		System.out.println("set中的元素为: ");
		Iterator it = set.iterator();
		while(it.hasNext()) {
			System.out.print(it.next() + " ");
		}
		System.out.println();
		System.out.println("**************************");
		// 添加重复元素, 不报错不显示
		set.add("red");
		it = set.iterator();
		
		while(it.hasNext()) {
			System.out.print(it.next() + " ");
		}	
	}
}

案例(对象):创建宠物猫

Cat.java

package com.csdn.set;

public class Cat {
	private String name;
	private int month;
	private String species;
	
	// 构造方法
	public Cat() {
		
	}

	public Cat(String name, int month, String species) {
		super();
		this.name = name;
		this.month = month;
		this.species = species;
	}

	// setter/getter方法
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getMonth() {
		return month;
	}

	public void setMonth(int month) {
		this.month = month;
	}

	public String getSpecies() {
		return species;
	}

	public void setSpecies(String species) {
		this.species = species;
	}

	@Override
	public String toString() {
		return "Cat [姓名=" + name + ", 年龄=" + month + ", 品种=" + species + "]";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + month;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + ((species == null) ? 0 : species.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj.getClass() == Cat.class) {
			Cat cat = (Cat) obj;
			return cat.getName().equals(name) && (cat.getMonth() == month) && cat.getSpecies().equals(species);
		}
		return false;
	}	
}

创建测试 CatTest.java

package com.csdn.set;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class CatTest {

	public static void main(String[] args) {
		// 定义宠物猫对象
		Cat huahua = new Cat("花花", 1, "英短");
		Cat fanfan = new Cat("凡凡", 10, "美短");
		// 将宠物猫对象放入HashSet中
		Set set = new HashSet();
		set.add(huahua);
		set.add(fanfan);
		// 显示宠物猫信息
		Iterator it = set.iterator();
		while(it.hasNext()) {
			System.out.println(it.next());
		}
		System.out.println("*********************");
		// 添加重复宠物信息
		Cat huahua01 = new Cat("花花", 1, "英短");
		set.add(huahua01);
		it = set.iterator();
		while(it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

五、Map 集合

  • Map中的数据是以键值对(key-value)的形式存储的
  • key-value以Entry类型的对象实例存在
  • 可以通过key值快速地查找value
  • 一个映射不能包含重复的键
  • 每个键最多只能映射到一个值

HashMap

  • 基于哈希表的Map接口实现
  • 允许使用null值和null键
  • key值不允许重复
  • HashMap重的Entry对象是无序排列的

案例:String对象

package com.csdn.set;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;

public class DictionaryDemo {

	public static void main(String[] args) {
		Map<String, String> animal = new HashMap<String, String>();
		System.out.println("请输入三组单词对应的注释, 并存放到HashMap中");
		Scanner console = new Scanner(System.in);
		// 添加数据
		int i = 0;
		while(i < 3) {
			System.out.print("请输入key值(单词): ");
			String key = console.next();
			System.out.print("请输入value值(注释): ");
			String value = console.next();
			animal.put(key, value);
			i++;
		}
		// 打印输出value的值(直接使用迭代器)
		System.out.println("******************************");
		System.out.println("使用迭代器输入所有的value: ");
		Iterator<String> it = animal.values().iterator();
		while(it.hasNext()) {
			System.out.print(it.next() + " ");
		}
		System.out.println("******************************");
		// 打印输出key和value的值
		// 通过entrySet方法
		System.out.println("通过entrySet方法得到key-value: ");
		Set<Entry<String, String>> entrySet = animal.entrySet();
		for (Entry<String, String> entry: entrySet) {
			System.out.print(entry.getKey() + "-");
			System.out.println(entry.getValue());
		}
		
		System.out.println("******************************");
		// 通过单词找到注释并输出
		// 使用keySet方法
		System.out.print("请输入要查找的单词:");
		String strSearch = console.next();
		// 1、取得keySet
		Set<String> keySet = animal.keySet();
		// 2、遍历keySet
		for(String key:keySet) {
			if(strSearch.equals(key)) {
				System.out.println("找到了! 键值对为:" + key + "-" + animal.get(key));
				break;
			}
		}	
	}
}

相关文章