- package com.cg.test;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Set;
- /*class Student{
- String name;
- int age;
- Student(String name,int age){
- this.name=name;
- this.age=age;
- }
- }*/
- class Work{
-
- }
- class Producer{
-
- }
- class Utils<QQ>{
- QQ qq;
- public void setObject(QQ qq){
- this.qq=qq;
- }
- public QQ getObject(){
- return qq;
- }
- }
- public class MapTestDemo {
- public static void main(String[] args) {
- showMap();
- }
- public static void showMap(){
- Map<Student, String> map =new HashMap<Student, String>();
-
- Utils<Student> utils1=new Utils<Student>();
- Utils<Student> utils2=new Utils<Student>();
- Utils<Student> utils3=new Utils<Student>();
-
- utils1.setObject(new Student("小明", 20));
- utils2.setObject(new Student("张山", 21));
- utils3.setObject(new Student("小四", 22));
-
- Student student1=utils1.getObject();
- Student student2=utils2.getObject();
- Student student3=utils3.getObject();
-
- map.put(student1, "武汉大学");
- map.put(student2, "清华大学");
- map.put(student3, "华中师范");
- Set<Student> s=map.keySet();
- Iterator<Student> it=s.iterator();
- while(it.hasNext()){
- Student s1=it.next();
- String s2=map.get(s1);
- System.out.println(s2);
- }
- Set<Map.Entry<Student, String>> set=map.entrySet();
- Iterator<Map.Entry<Student, String>> iterator=set.iterator();
- while(iterator.hasNext()){
- Map.Entry<Student, String> mapEntry=iterator.next();
- Student student=mapEntry.getKey();
- String string=mapEntry.getValue();
- System.out.println(student.name+":"+student.age);
- System.out.println(string);
- }
-
- }
-
- }
复制代码 想问下,如果定义了一个Utils工具泛型类,在每次添加元素的时候,都需要new一个行的Utils对象么,这样做是不是效率很低呢?既然这样很麻烦为什么还要定义这样一个工具类呢?在每次添加一个学生类对象都要通过Utils获取一个学生类对象,感觉好麻烦,求解答!
|