Java高级语法笔记-HashMap

哈希表HashMap中可以存储N个对象,每个对象由一个唯一的Key值关联。

哈希表主要用于快速查找
那么,怎么样查找才算是“快速”?
假设有1000个Student对象,
(1) 放在ArrayList里
用indexOf查找,是按顺序从前往后找一遍,最多要比较1000次
(2) 放在HashMap里
用get获取,不是逐个比较,而是直接由Key值取得相应的对象。。。速度快


代码如下:

HelloWord.java

package my;

import java.util.HashMap;
import java.util.ArrayList;

public class HelloWorld
{
	public static void main(String[] args)
	{		
		HashMap studentHash=new HashMap();
		studentHash.put(1000, new Student(1000,"球球","14523652345"));
		studentHash.put(1001, new Student(1001,"腿腿","12356231256"));
		studentHash.put(1002, new Student(1002,"闰土","14567821256"));
		studentHash.put(1003, new Student(1003,"妹爷","18792157456"));
		
		Student value=studentHash.get(1000);
		if(value!=null) System.out.println("found:"+value.toString());
		studentHash.remove(1000);
		value=studentHash.get(1000);
		if(value==null)	System.out.println("没有找到球球");
		
		System.out.println("打印所有Hash表:");
		for(Student e : studentHash.values())
			System.out.println("got:"+e);
		
		//不需要定义Student类型,直接用HashMap表示一个学生相关数据,把HashMap当成一个通用的“结构体”来使用
		HashMap row=new HashMap();
		row.put("id", 1000);
		row.put("name","球球");
		
		ArrayList studentList=new ArrayList();
		studentList.add(row);
	} 
}


Student.java

package my;

public class Student
{
	int id;
	String name;
	String phone;
	public Student(int id,String name, String phone) {
		this.id=id;
		this.name=name;
		this.phone=phone;
	}
	@Override
	public boolean equals(Object obj)
	{
		Student other=(Student)obj;
		//return other.id==this.id;
		
		//如果用name的话
		return other.name.equals(this.name);
	}
	@Override
	public String toString()
	{
		return "("+id+","+name+","+phone+")";
	}
}

运行截图如下:

Java高级语法笔记-HashMap_第1张图片


你可能感兴趣的:(Java,我的Java地带)