动手实现集合框架-HashSet、HashMap

本文深入探讨了Java集合框架中的HashSet和HashMap的工作原理,包括它们的遍历方式、内部实现机制,以及如何自定义字符串的hashCode方法。同时,文章还介绍了自定义HashMap的实现过程,并讨论了比较器Comparator和Compareable接口在集合排序中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HashSet

遍历:

Set不提供get()来获取指定位置的元素,所以遍历需要用到迭代器,或者增强型for循环。

import java.util.HashSet;
import java.util.Iterator;
  
public class TestCollection {
    public static void main(String[] args) {
         
        HashSet<Integer> numbers = new HashSet<Integer>();
        
        for (int i = 0; i < 20; i++) {
        	numbers.add(i);
        }
        
        // Set不提供get方法来获取指定位置的元素
        // The method get(int) is undefined for the type HashSet<Integer>
//      numbers.get(0);
        
        // 遍历Set可以采用迭代器iterator
        for (Iterator<Integer> iterator = numbers.iterator(); iterator.hasNext();) {
        	Integer i = (Integer) iterator.next();
        	System.out.println(i);
        }
        
        //或者采用增强型for循环
        for (Integer i : numbers) {
        	System.out.println(i);
        }
    }
}

HashSet 和 HashMap

HashSet自身没有独立的实现,而是在里面封装了一个Map。

HashSet是作为Map的key而存在的,而value是一个命名为PRESENT的Object对象,因为是一个类属性,所以只会有一个。

private static final Object PRESENT = new Object();

部分源码:

import java.util.AbstractSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
 
public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable
{
    //HashSet里封装了一个HashMap
    private  HashMap<E,Object> map;
 
    private static final Object PRESENT = new Object();
 
    //HashSet的构造方法初始化这个HashMap
    public HashSet() {
        map = new HashMap<E,Object>();
    }
 
    //向HashSet中增加元素,其实就是把该元素作为key,增加到Map中
    //value是PRESENT,静态,final的对象,所有的HashSet都使用这么同一个对象
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
 
    //HashSet的size就是map的size
    public int size() {
        return map.size();
    }
 
    //清空Set就是清空Map
    public void clear() {
        map.clear();
    }
     
    //迭代Set,就是把Map的键拿出来迭代
    public Iterator<E> iterator() {
        return map.keySet().iterator();
    }
 
}

自定义字符串的hashCode

public class TestCollection {
    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
        	int length = (int) (Math.random() * 8 + 2);
        	String str = randomString(length);
        	int hashcode = hashCode(str);
        	System.out.printf("%-11s的自定义hashcode是:%d%n", str, hashcode);
        }
    }

	private static int hashCode(String str) {
		if (0 == str.length()) {
			return 0;
		}
		
		int hashcode = 0;
		char[] cs = str.toCharArray();
		for (int i = 0; i < cs.length; i++) {
			hashcode += cs[i];
		}
		hashcode *= 23;
		// 取绝对值
		hashcode = hashcode < 0 ? 0 - hashcode : hashcode;
		// 落在0-1999之间
		hashcode %= 2000;
		return hashcode;
	}

	private static String randomString(int length) {
		String pool = "";
		for (short i = '0'; i < '9'; i++) {
			pool += (char) i;
		}
		for (short i = 'a'; i <= 'z'; i++) {
			pool += (char) i;
		}
		for (short i = 'A'; i < 'Z'; i++) {
			pool += (char) i;
		}
		char[] cs = new char[length];
		for (int i = 0; i < cs.length; i++) {
			int index = (int) (Math.random() * pool.length());
			cs[i] = pool.charAt(index);
		}
		String result = new String(cs);
		return result;
	}
}

自定义MyHashMap

根据hashcode的原理和自定义hashcode,设计一个MyHashMap,实现接口IHashMap。

MyHashMap内部由一个长度为2000的对象数据实现。

设计 put(String key, Object vlaue) 方法:

  • 首先通过自定义字符串的hashcode方法获取到该字符串的hashcode,然后把这个hashcode作为下标,定位到数组的指定位置。
  • 如果该位置没有数据,则把字符串和对象合成键值对Entry,再创建一个LinkedList,把键值对,放进LinkedList中,最后把LinkedList保存在这个位置。
  • 如果该位置有数据,一定是一个LinkedList,则把字符串和对象组合成键值对Entry,插入到LinkedList后面。

设计 Object get(String key) 方法

  • 首先通过自定义字符串的hashcode方法获取到该字符串的hashcode,然后把hashcode作为下标,定位到数组的指定位置。
  • 如果这个位置没有数据,则返回空。
  • 如果这个位置有数据,则挨个比较其中键值对的键-字符串,是否equals,找到匹配的,把键值对的值,返回出去。找不到匹配的,就返回空。

IHashMap 接口:

public interface IHashMap {
	public void put(String key, Object object);
	public Object get(String key);
}

Entry 类:

//键值对
public class Entry {
	public Entry (Object key, Object value) {
		super();
		this.key = key;
		this.value = value;
	}
	public Object key;
	public Object value;
	public String toString() {
		return "[key = " + key + ", value = " + value + "]";
	}
}

HashMap实现:

import java.util.LinkedList;

public class MyHashMap implements IHashMap {
	LinkedList<Entry>[] values = new LinkedList[2000];

	@Override
	public void put(String key, Object object) {
		// 拿到hashcode
		int hashcode = hashcode(key);
		// 找到对应的LinkedList
		LinkedList<Entry> list = values[hashcode];
		// 如果LinkedList是null,则创建一个LinkedList
		if(null == list) {
			list = new LinkedList<>();
			values[hashcode] = list;
		}
		// 判断该key是否已经有对应的键值对
		boolean found = false;
		for (Entry entry : list) {
			// 如果已经有了,则替换掉
			if (key.equals(entry.key)) {
				entry.value = object;
				found = true;
				break;
			}
		}
		// 如果没有已经存在的键值对,则创建新的键值对
		if (!found) {
			Entry entry = new Entry(key, object);
			list.add(entry);
		}		
	}

	private int hashcode(String str) {
		if (0 == str.length())
            return 0;
 
        int hashcode = 0;
        char[] cs = str.toCharArray();
        for (int i = 0; i < cs.length; i++) {
            hashcode += cs[i];
        }
        hashcode *= 23;
        // 取绝对值
        hashcode = hashcode < 0 ? 0 - hashcode : hashcode;
        // 落在0-1999之间
        hashcode %= 2000;
 
        return hashcode;
	}

	@Override
	public Object get(String key) {
		// 获取hashcode
		int hashcode = hashcode(key);
		// 找到hashcode对应的LinkedList
		LinkedList<Entry> list = values[hashcode];
		if (null == list) {
			return null;
		}
		Object result = null;
		// 挨个比较每个键值对的key,找到匹配的,返回其value
		for (Entry entry : list) {
			if (entry.key.equals(key)) {
				result  = entry.value;
				break;
			}
		}
		return result;
	}
	
	public String toString() {
		LinkedList<Entry> result = new LinkedList();
		
		for (LinkedList<Entry> linkedList : values) {
			if (null == linkedList) {
				continue;
			}
			result.addAll(linkedList);
		}
		return result.toString();
	}
	
	public static void main(String[] args) {
		MyHashMap map =new MyHashMap();
        
         map.put("t", "坦克");
         map.put("adc", "物理");
         map.put("apc", "魔法");
         map.put("t", "坦克2");
        
         System.out.println(map.get("adc"));
        
         System.out.println(map);
         
         System.out.println(map.hashcode("name=hero-2387"));
         System.out.println(map.hashcode("name=hero-5555"));
		
	}
	
}

比较器

假设Hero有三个属性 name,hp,damage

1. Comparator

一个集合中放存放10个Hero,通过Collections.sort对这10个进行排序。那么到底是hp小的放前面?还是damage小的放前面?Collections.sort也无法确定。

所以要指定到底按照那种属性进行排序,这就需要提供一个Comparator给定如何进行两个对象之间的大小比较。

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
    
import charactor.Hero;
     
public class TestCollection {
    public static void main(String[] args) {
        Random  r = new Random();
        List<Hero> heros = new ArrayList<Hero>();
        for (int i = 0; i < 10; i++) {
        	// 通过随机值实例化hero的hp和damage
        	heros.add(new Hero("hero " + i, r.nextInt(100), r.nextInt(100)));
        }
        System.out.println("初始化后的集合");
        System.out.println(heros);
        
        // 直接调用sort会出现编译错误,因为hero有各种属性
        // 到底按照哪种属性进行比较,Collections也不知道,不确定,所以没法排
//        Collections.sort(heros);
        
        // 引入Comparator,指定比较的算法
        Comparator<Hero> c = new Comparator<Hero>() {

			@Override
			public int compare(Hero h1, Hero h2) {
				// 按照damage进行排血
				if (h1.damage >= h2.damage) {
					return 1; // 正数表示h1比h2要大
				}else {
					return -1;
				}
			}
        };
        Collections.sort(heros,c);
        System.out.println("按照伤害排序后的集合");
        System.out.println(heros);
    }
}

2. Compareable

使Hero类实现Comparable接口。在类里面实现比较算法。Collection.sort就有足够的信息进行排序了,也无需额外提供比较器Comparator。

注:如果返回-1,就表示当前的对象更小,否则就是更大。

Hero类:

public class Hero implements Comparable<Hero> {
    public String name;
    public float hp;
  
    public int damage;
  
    public Hero() {
    	
    }
  
    public Hero(String name) {
        this.name = name;
    }
    
    // 初始化name,hp,damage的构造方法
    public Hero (String name, float hp, int damage) {
    	this.name = name;
    	this.hp = hp;
    	this.damage = damage;
    }

	@Override
	public int compareTo(Hero anotherHero) {
		if (hp < anotherHero.hp) {
			return 1;
		}else {
			return -1;
		}
	}
	
	public String toString() {
        return "Hero [name=" + name + ", hp=" + hp + ", damage=" + damage + "]\r\n";
    }
}

测试代码:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
    
import charactor.Hero;
     
public class TestCollection {
    public static void main(String[] args) {
        Random  r = new Random();
        List<Hero> heros = new ArrayList<Hero>();
        for (int i = 0; i < 10; i++) {
        	// 通过随机值实例化hero的hp和damage
        	heros.add(new Hero("hero " + i, r.nextInt(100), r.nextInt(100)));
        }
        System.out.println("初始化后的集合");
        System.out.println(heros);
        
        // Hero类实现了Comparable,即自带比较信息
        // Collections直接进行排序,无需额外的Comparator
        Collections.sort(heros);
        System.out.println("按照血量排序后的集合");
        System.out.println(heros);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值