終極HashSet HashMap TreeSet TreeMap深入分析下
最常用的
Map<String,String> map =new HashMap<String,String>();
System.out.println("常用=============="); 這是最常用的
map.put("NO01", "常智皓");
map.put("NO02", "賈寶玉");
map.put("NO01", "常偉");
map.put(null, null);
map.put(null, "劉優");
System.out.println(map);
String name =map.get("NO01");
System.out.println(name);
如果新增物件的話就要實現 comparable介面 或者自定義一個類繼承comparator
Map<our, String> map4 = new TreeMap<our, String>(new myc()); //括號中是自定義類的例項化 如果1、2倆中方法都是用了則預設使用構造方法裡的排列方式
map4.put(new our(1,"aaa"), "1");
map4.put(new our(2,"bbb"), "2");
map4.put(new our(3,"ccc"), "3");
System.out.println(map4);
實現介面 implements Comparable<our>
@Override
public int compareTo(our o) {
// TODO Auto-generated method stub
if(this.id > o.id) {
return 1;
}else if (this.id < o.id) {
return -1;
}
return 0;
}
自定義類
class myc implements Comparator<our>{
@Override
public int compare(our o1, our o2) {
// TODO Auto-generated method stub
return o2.getId() - o1.getId() ;
}
}
our全部類
class our implements Comparable<our>{
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "our [id=" + id + ", name=" + name + "]";
}
public our(int id, String name) {
super();
this.id = id;
this.name = name;
}
@Override
public int compareTo(our o) {
// TODO Auto-generated method stub
if(this.id > o.id) {
return 1;
}else if (this.id < o.id) {
return -1;
}
return 0;
}
}