第一种:
Map map = new HashMap();
Iterator iter = mapentrySet()iterator();
while (iterhasNext()) {
MapEntry entry = (MapEntry) iternext();
Object key = entrygetKey();
Object val = entrygetValue();
}
效率高,以后一定要使用此种方式!
第二种:
Map map = new HashMap();
Iterator iter = mapkeySet()iterator();
while (iterhasNext()) {
Object key = iternext();
Object val = mapget(key);
}
效率低,以后尽量少使用!
HashMap的遍历有两种常用的方法,那就是使用keyset及entryset来进行遍历,但两者的遍历速度是有差别的,下面请看实例:
public class HashMapTest {
public static void main(String[] args) {
HashMap hashmap = new HashMap();
for (int i = 0; i < 1000; i ) {
hashmapput("" i, "thanks");
}
long bs = CalendargetInstance()getTimeInMillis();
Iterator iterator = hashmapkeySet()iterator();
while (iteratorhasNext()) {
Systemoutprint(hashmapget(iteratornext()));
}
Systemoutprintln();
Systemoutprintln(CalendargetInstance()getTimeInMillis() - bs);
listHashMap();
}
public static void listHashMap() {
javautilHashMap hashmap = new javautilHashMap();
for (int i = 0; i < 1000; i ) {
hashmapput("" i, "thanks");
}
long bs = CalendargetInstance()getTimeInMillis();
javautilIterator it = hashmapentrySet()iterator();
while (ithasNext()) {
javautilMapEntry entry = (javautilMapEntry) itnext();
// entrygetKey() 返回与此项对应的键
// entrygetValue() 返回与此项对应的值
Systemoutprint(entrygetValue());
}
Systemoutprintln();
Systemoutprintln(CalendargetInstance()getTimeInMillis() - bs);
}
}
对于keySet其实是遍历了2次,一次是转为iterator,一次就从hashmap中取出key所对于的value。而entryset只是遍历了第一次,他把key和value都放到了entry中,所以就快了。
注:Hashtable的遍历方法和以上的差不多!
进行实例分析一下下:
以下通过程序来简单实践一下HashMap的的遍历
如果要保持HashMap的遍历顺序和原插入顺序一致,可以使用LinkedHashMap,使用方法和HashMap一样,改一下声明即可:LinkedHashMap myMap = new LinkedHashMap(); 当然需要导入:javautilLinkedHashMap
import javautilCollection;
import javautilHashMap;
import javautilIterator;
import javautilMap;
public class MapList {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap myMap = new HashMap();
myMapput("hello", "");
myMapput("bye", "再见");
myMapput("thanks", "");
myMapput("ok", "好的");
Systemoutprintln("--------------------遍历key和value----------------------");
for(Iterator iter = myMapentrySet()iterator();iterhasNext();){
MapEntry element = (MapEntry)iternext();
Object strKey = elementgetKey();
Object strObj = elementgetValue();
Systemoutprintln("myMapget(\""+strKey+"\")="+strObj);
}
Systemoutprintln();
Systemoutprintln("--------------------遍历整个HashMap----------------------");
Collection objs = myMapentrySet();
for (Iterator iterator=objsiterator(); iteratorhasNext();){
Object obj = iteratornext();
Systemoutprintln(obj);
}
Systemoutprintln();
Systemoutprintln("--------------------遍历HashMap的key----------------------");
Collection keys = myMapkeySet();
for (Iterator iterator=keysiterator(); iteratorhasNext();){
Object key = iteratornext();
Systemoutprintln(key);
}
Systemoutprintln();
Systemoutprintln("--------------------遍历HashMap的value----------------------");
Collection values = myMapvalues();
for (Iterator iterator=valuesiterator(); iteratorhasNext();){
Object value = iteratornext();
Systemoutprintln(value);
}
}
}
运行结果:
--------------------遍历key和value----------------------
myMapget("hello")=
myMapget("thanks")=
myMapget("ok")=好的
myMapget("bye")=再见
--------------------遍历整个HashMap----------------------
hello=
thanks=
ok=好的
bye=再见
--------------------遍历HashMap的key----------------------
hello
thanks
ok
bye
--------------------遍历HashMap的value----------------------
好的
再见
乱码?????你加个tostring方法,不是乱不乱码,一看就是菜鸟
package image;
import javautilArrayList;
import javautilHashMap;
import javautilList;
import javautilMap;
public class Movie3
{
int movieId;
String movieName;
double price;
public Movie3 ( int movieId, String movieName, double price )
{
thismovieId = movieId;
thismovieName = movieName;
thisprice = price;
}
public int getID ()
{
return movieId;
}
public String getMovieName ()
{
return movieName;
}
public double getPrice ()
{
return price;
}
@Override
public String toString ()
{
StringBuilder builder = new StringBuilder ();
builderappend ("Movie3 [movieId=");
builderappend (movieId);
builderappend (", movieName=");
builderappend (movieName);
builderappend (", price=");
builderappend (price);
builderappend ("]");
return buildertoString ();
}
public static void main ( String[] args )
{
Movie3 a = new Movie3 (1, "冰雪奇缘", 40);
Movie3 b = new Movie3 (2, "美国队长2", 40);
Movie3 c = new Movie3 (3, "大闹天宫", 50);
Movie3 d = new Movie3 (4, "卑鄙的我2", 50);
List sciencemovieDVDList = new ArrayList ();
List AnimationmovieDVDList = new ArrayList ();
sciencemovieDVDListadd (b);
sciencemovieDVDListadd (c);
AnimationmovieDVDListadd (a);
AnimationmovieDVDListadd (d);
Map movies = new HashMap ();
moviesput ("科幻**", sciencemovieDVDList);
moviesput ("动漫**", AnimationmovieDVDList);
Systemoutprintln ("键的集合" + movieskeySet ());
Systemoutprintln ("键-值对集合:" + movies);
String key = "科幻**";
if (moviescontainsKey (key))
{
Systemoutprintln ("键“" + key + "”对应的值:" + moviesget (key));
}
moviesremove (key);
Systemoutprintln ("键-值”对集合:" + movies);
}
}
HashMap 计算方法为:(n - 1) & hash 具体见putVal
解读:由于n-1高位全部为0 因此(n - 1) & hash只会得到一个小于等于n-1的值,即在桶长度取值范围内
为何不用取余运算,写一段模拟程序,我们来对比下速度:
运行结果:
我们把数字改成5
&位运算速度快于%,缺点:某些奇数如5 时分布不均匀。
联系下另一个方法:tableSizeFor 会将我们传入容量返回为2的倍数。经过实际测试 16 ,32 &位运算比较均匀。
给你发一个完整的吧,反正我电脑上有,
/
存储关联的键值对
@param key:键
@param value:值
@return
/
public V put(K key, V value) {
//当键值为null时,调用putForNullKey(value)的方法存储,
//在该方法中调用recordAccess(HashMap<K,V> m)的方法处理
if (key == null)
return putForNullKey(value);
//根据key的KeyCode,计算hashCode
int hash = hash(keyhashCode());
//调用indexFor方法,返回hash在对应table中的索引(Entry[] table)
int i = indexFor(hash, tablelength);
//当i索引处的Entry不为null时,遍历下一个元素
for (Entry<K,V> e = table[i]; e != null; e = enext) {
Object k;
//如果遍历到的hash值等于根据Key值计算出的hash值并且
//key值与需要放入的key值相等时,存放与key对应的value值
if (ehash == hash && ((k = ekey) == key || keyequals(k))) {
//覆盖oldValue的值
V oldValue = evalue;
evalue = value;
erecordAccess(this);
return oldValue;
}
}
modCount++;
//当i索引处的Entry为null时,将指定的key、value、hash条目放入到指定的桶i中
//如果现有HashMap的大小大于容量负载因子时,resize(2 tablelength);
addEntry(hash, key, value, i);
return null;
}
/实例化HashMap对象
HashMap<String,String> hashMap=new HashMap<String,String>();
//1、将Map接口变为Set接口
Set<MapEntry<String,String>> set=hashMapentrySet();
//2、实例化Iterator接口
Iterator it=setiterator();
while(ithasNext()){
//3、得到存储在HashMap中的Entry对象
MapEntry<String,String> me=(Entry<String, String>) itnext();
//4、通过Entry得到key和value
Systemoutprintln("Key="+megetKey()+"Value="+megetValue());
}
HashMap<Student,String> map=new HashMap<Student,String>();
mapput(new Student("1608100201","Jony"), "CSU");
Systemoutprintln(mapget(stu));
//实例化一个学生对象
Student stu=new Student("1608100201","Jony");
HashMap<Student,String> map=new HashMap<Student,String>();
mapput(stu, "CSU");
Systemoutprintln(mapget(stu));
public class Student {
//学生的学号属性
public static String ID;
//学生的姓名属性
private String name;
/
重载构造方法
/
public Student(String ID,String name){
thisID=ID;
thisname=name;
}
/
覆写equals()方法
/
public boolean equals(Object obj) {
//判断地址是否相等
if(this==obj){
return true;
}
//传递进来用于比较的对象不是本类的对象
if (!(obj instanceof Student))
return false;
//向下转型
Student stu = (Student)obj;
//比较属性内容是否相等
if (thisIDequals(stuID)&&thisnameequals(stuname)) {
return true;
}
return false;
}
/
覆写hashCode()方法
/
public int hashCode() {
return thisIDhashCode();
}
}
祝你好运了!~
java中HashMap类是用来存储具有键值对特征的数据。例如现在需要按照员工号来存储大量的员工信息,那么就可以使用HashMap,将员工号作为键,员工对象作为值来存储到HashMap中,其中使用HashMap时需要注意,HashMap是线程不同步的,多线程使用时,需要注意;并且HashMap允许null值作为键和值。
import javaxswing;
import javaawt;
import javaawtevent;
import javautil;
import combruceeckelswing;
public class TrackEvent extends JApplet {
private HashMap h = new HashMap();
private String[] event = {
"focusGained", "focusLost", "keyPressed",
"keyReleased", "keyTyped", "mouseClicked",
"mouseEntered", "mouseExited", "mousePressed",
"mouseReleased", "mouseDragged", "mouseMoved"
};
private MyButton
b1 = new MyButton(ColorBLUE, "test1"),
b2 = new MyButton(ColorRED, "test2");
class MyButton extends JButton {
void report(String field, String msg) {
((JTextField)hget(field))setText(msg);
}
FocusListener fl = new FocusListener() {
public void focusGained(FocusEvent e) {
report("focusGained", eparamString());
}
public void focusLost(FocusEvent e) {
report("focusLost", eparamString());
}
};
KeyListener kl = new KeyListener() {
public void keyPressed(KeyEvent e) {
report("keyPressed", eparamString());
}
public void keyReleased(KeyEvent e) {
report("keyReleased", eparamString());
}
public void keyTyped(KeyEvent e) {
report("keyTyped", eparamString());
}
};
MouseListener ml = new MouseListener() {
public void mouseClicked(MouseEvent e) {
report("mouseClicked", eparamString());
}
public void mouseEntered(MouseEvent e) {
report("mouseEntered", eparamString());
}
public void mouseExited(MouseEvent e) {
report("mouseExited", eparamString());
}
public void mousePressed(MouseEvent e) {
report("mousePressed", eparamString());
}
public void mouseReleased(MouseEvent e) {
report("mouseReleased", eparamString());
}
};
MouseMotionListener mml = new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
report("mouseDragged", eparamString());
}
public void mouseMoved(MouseEvent e) {
report("mouseMoved", eparamString());
}
};
public MyButton(Color color, String label) {
super(label);
setBackground(color);
addFocusListener(fl);
addKeyListener(kl);
addMouseListener(ml);
addMouseMotionListener(mml);
}
}
public void init() {
Container c = getContentPane();
csetLayout(new GridLayout(eventlength + 1, 2));
for(int i = 0; i < eventlength; i++) {
JTextField t = new JTextField();
tsetEditable(false);
cadd(new JLabel(event[i], JLabelRIGHT));
cadd(t);
hput(event[i], t);
}
cadd(b1);
cadd(b2);
}
public static void main(String[] args) {
Consolerun(new TrackEvent(), 700, 500);
}
}
以上就是关于如何遍历linkedhashmap全部的内容,包括:如何遍历linkedhashmap、怎么遍历HashMap中的ArrayList,运行结果乱码了,程序在下面。求大神支援、HashMap下标计算详解等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)