Use HashMap and For loop to find data and count time-consuming

Prepare an ArrayList which stores 3000000 (three million) Hero objects, whose name is random, and the format is hero-[4-digit random number]
hero-3229
hero-6232
hero-9365
...
Because the total number is very large, so almost There are duplicates of each kind. Find out all the objects named hero-5555.
Two methods are required to find
1. Do not use HashMap, directly use the for loop to find out, and count the time spent
2. Use HashMap to find the result And count the time spent

package ArrayList;

public class Hero {
	 String name; //姓名    
	    float hp; //血量        
	    float armor; //护甲	        
	    int moveSpeed; //移动速度	     
	    public Hero(){	         
	    }
	    public Hero(String name) {
	    	this.name=name; 	
	    }	    
	    public String toString() {
	    	return name;
	    }	    
}
package hashMap;
import java.util.ArrayList;
import java.util.List;
import ArrayList.Hero;
import java.util.HashMap;
import java.util.Date;
public class 练习 {
public static void main(String[] args) {
	List<Hero> randomHero =new ArrayList<>();
for(int i=0;i<3000000;i++) {
	int randomFigure=(int)(Math.random()*9000+1000);
	String randomName="hero-"+randomFigure;
	Hero h=new Hero(randomName);
	randomHero.add(h);	
}

Long time1=new Date().getTime();
List<Hero> getByFor=new ArrayList<>();
for(Hero heros:randomHero) {
	if(heros.equals("hero-5555")) {
		getByFor.add(heros);
	}
}
//int range1=getByFor.size();
//System.out.println("for循环的查找结果为:"+range1);
System.out.println(getByFor);
System.out.println("for循环耗费时间:"+(Long)(new Date().getTime()-time1));

Long time2=new Date().getTime();
List<String> getByHashMap=new ArrayList<>();
HashMap<String,String> hashHero = new HashMap<>();
for(int j=0;j<3000000;j++) {
	int randomFigure=(int)(Math.random()*9000+1000);
	String randomName="hero-"+randomFigure;
	hashHero.put(randomName,randomName);
}
getByHashMap.add(hashHero.get("hero-5555"));
//int range2=getByHashMap.size();
//System.out.println("HashMap的查找结果为:"+range2);
System.out.println(getByHashMap);
System.out.println("HashMap耗费时间:"+(Long)(new Date().getTime()-time2));

}
}

This problem has not been solved. I don't know why the result of the for loop is always zero, and the HashMap is always one. Big guy help........

Guess you like

Origin blog.csdn.net/qq_44624536/article/details/113818947