一、HashMap的遍历:
1、第一种方式:(效率比较高:只遍历了一次,把key和value都放在了entry中)
①HashMap map = new HashMap();
Iterator iter = mapentrySet()iterator();
while(iterhasNext()){
MapEntry entry = (MapEntry)iternext();
Object key = entrygetKey();
Object val = entrygetValue();
}
2、第二种方式:(效率较低:keySet其实是遍历了2遍,一次转换成iterator,一次从hasgmap中取出Key所对于的value
Map map = new HashMap();
Iterator iter = mapkeySet()itertor();
while(iterhasNext()){
Object key = iternext();
Object val = mapget(key);
}
2017/12/19
一、foreach的使用:
1、foreach 是java5的新特性之一,在遍历数组,集合方面有很大用处。foreach不是一个关键词,而是把增强型的for语句称为foreach语句。
2、结构是: for(part1 : part2){ part3 }
例如:
for (NotifyEntity entity : mUnreadNoticeList) {
counts = counts + entitygetNotifyCount();
}
hashmap得containskey相比而言比较查询比较高,毕竟hashmap是基于哈希表的,哈希函数不是盖出来的,在对付数据查找的时候效率挺高的。
listcontains方法其实调用的是indexof(obj)方法,需要遍历整个list,运气差就要遍历所有list
乱码?????你加个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的遍历和foreach的使用全部的内容,包括:HashMap的遍历和foreach的使用、HashMap里的containsKey方法和List里的contains方法,哪个效率高、怎么遍历HashMap中的ArrayList,运行结果乱码了,程序在下面。求大神支援等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)