1java遍历List、Set、Map
List<String> list = new ArrayList<String>();
list.add(“张三”);
list.add(“李四”);
list.add(“王五”);
//通过Iterator 迭代器遍历列表+"/n"
Iterator<String> it = list.iterator();
while(it.hasnext) {
System.out.println(it.next);
}
Set<String> set = new HashSet<String>();
set.add(“张三”);
set.add(“李四”);
set.add(“王五”);
Iterator<String> it = set.iterator();
while(it.hasnext) {
System.out.println(it.next);
}
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, “小希”);
map.put(2, “美美”);
map.put(3, “空城”);
Set<Integer> keys = map.keySet();
for(Integer key : keys) {
String value = map.get(key);
System.out.println(key+” ”+value);
}
通过java.Math包的random方法得到1-10的int随机数
(int)(1+Math.random()*10)
单例模式的代码
//饿汉式单例模式
public class Singleton {
private final static Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return s;
}
}
//懒汉式
public class Singleton {
private static Singleton instance;
static {
instance = new Singleton();
}
private Singleton() {}
public Singleton getInstance() {
return instance;
}
}
public class Singleton {
private static Singleton singleton;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}