黑马程序员技术交流社区
标题:
集合框架中Utils中的一些问题,求解答
[打印本页]
作者:
向日葵的曙光
时间:
2014-4-21 16:56
标题:
集合框架中Utils中的一些问题,求解答
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获取一个学生类对象,感觉好麻烦,求解答!
作者:
Silvester
时间:
2014-4-21 18:51
有个addAll( )方法可以接受一个Collection对象,或者一个数组或者一个用逗号分隔的列表,你可以把要添加的对象存在二维数组中用addAll( )方法。
或者是用数组Arrays的asList( )方法返回一个受指定数组支持的固定大小的列表。
目前为止就知道这两种方法,也许接着往后学会有新的方法吧,也希望有高手能提供!
作者:
向日葵的曙光
时间:
2014-4-21 20:02
问题是这两部怎么优化呀
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));
作者:
kevinmesss.tz
时间:
2014-4-21 20:16
把工具类Utils中的方法设置为static的,并且把学生对象也作为参数传递,这样就不用每次都new对象了
工具类一般没有特有的属性。才把方法设置成静态的
作者:
向日葵的曙光
时间:
2014-4-21 21:16
kevinmesss.tz 发表于 2014-4-21 20:16
把工具类Utils中的方法设置为static的,并且把学生对象也作为参数传递,这样就不用每次都new对象了
工具类 ...
那就失去了工具类的特性了呀,不然还要工具类干嘛!不就是定义一个泛型类就可以了么
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2