map
map中的key不能相同,后面相同的值会替换掉前面相同key的值。
唯一性是用哈希值保证的。
map.put("1","林青霞");
map.put("1","张曼玉");
//map中会只剩下第二个值。
V map.put();
V map.remove()
void map.clear(); //移除所有的值
boolean containsKey(Object key);//判断集合是否包含指定的键
boolean containsValue(Object value);//判断集合是否包含指定的值
int size();//集合的长度
V get(Object key);//根据键获取值
Set<K> keySet();//获取所有键的集合
Collection<V> values();//获取所有值的集合
Set<Map.Entry<K,V>> entrySet();//获取所有键值对对象的集合
map的遍历
Set<String> keySet=map.keySet();
for(String key:keySet){
String value=map.get(key);
sout(key,value);
}
Set<Map.Entry<String,String>> e=map.entrySet();
for(Map.Entry<String,String> me:e){
String key=me.getKey();
String value=me.getValue();
sout(key,value);
}
map的重写heshCode()和equals()
HashMap<Student,String> hm=new HashMap<Student,String>();
Student s1=new Student("林青霞",30);
Student s1=new Student("离青霞",31);
Student s1=new Student("力青霞",32);
hm.put(s1,"西安");
hm.put(s1,"西安");
hm.put(s1,"西安");
//在学生类中重写heshCode()和equals()
ArrayList和map
ArrayList<HashMap<String,String>> array=new ArrayList<HashMap<String,String>();
HashMap<String,String> hm1=new HashMap<String,String>();
hm1.put("1","1");
hm1.put("2","2");
hm1.put("3","3");
array.add(hm1);
for(HashMap<String,String> hm:array){
Set<String> keySet=hm.keySet();
for(String key:keySet){
String value=hm.get(key);
sout(key,value);
}
}
for(int i=0;i<line.length();i++){
char key=line.charAt(i);//将string中单个字符拆出
}
//使用StringBuilder拼接字符串
StringBuilder sb=new StringBuilder();
Set<Character> key=hm.keySet();
for(Character key:keySet){
Integer value=hm.get(key);
sb.append(key).append("(".append(value).append(")"));
}
String result=sb.toString();
sout(result);
Collections
//该类是集合类的工具类
List<Interget> list=new ArrayList<Interget>();
list.add(32);
list.add(30);
list.add(33);
list.add(31);
Collections.sort(list);//排序(默认从小到大)
Collections.reverse(list);//反转元素
Collections.shuffle(list);// 使用随机的排序(从小到大或者从大到小)
ArrayList存储对象并排序
ArrayList<Student> array=new ArrayList<Student>();
array.add(stu1);
array.add(stu2);
array.add(stu3);
//使用Collections对ArrayList进行排序,使用匿名内部类编写排序器
Collection.sort(array, new Comparator<Student>(){
public int compare(Student s1,Student s2){
int num=s1.getAge()-s2.getAge();
int num2= num==0?s1.getName().compareTo(s2.getName()):num;
return num2;
}
});