import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MapTest {
public static void main(String[] args) {
People p1 = new People("001",21);
People p2 = new People("002",33);
People p3 = new People("003",41);
Map<String,People>map=new HashMap<>();
map.put("001", p1);
map.put("002", p2);
map.put("003", p3);
Set<String>keys=map.keySet();
for(String key:keys) {
System.out.println("name="+key+",age="+map.get(key));
}
}
印出來的結果
name=001,age=People@2a139a55
name=002,age=People@15db9742
name=003,age=People@6d06d69c
想請教的地方是為何age印出來的不是p1p2p3裡面的數字呢
這跟泛型無關
map.get(key)
會拿出People
物件,阿print一個物件就是會顯示物件所在的記憶體位址(address),像是People@2a139a55
,這是告訴你print的物件為People
類別且在0x2a139a55
我猜你的People
物件應該有兩個屬性name
, age
,所以應該改為這樣
System.out.println("name="+key+",age="+map.get(key).age);
感謝回答,可是我並沒有去定義age是什麼東西,所以加在後面也是說方法錯誤
你要看你自定義People
類別內有甚麼,你沒貼出來我看不出來,只能猜測你的p1,p2,p3中的數字是存在叫做People.age
的屬性裡,或許你可以貼出People
類別的程式碼
public class People {
private String name;
private int age;
public People(String id, int age) {
this.name = id;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
也許是java程式儲存的方式
有時候java會儲存地址值就是記憶體的位子
如果你不要出現這個你可以先把地址值轉換成你的數據這樣他印出來就會是你要的值
所以你要修改的是People的輸出參數
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MapTest {
public static void main(String[] args) {
People p1 = new People("001",21);
People p2 = new People("002",33);
People p3 = new People("003",41);
****注意****這裡存的是**地址值**
System.out.println(p1);**//People@75412c2f**
****注意****這裡存的是**地址值**
Map<String,People>map=new HashMap<>();
map.put("001", p1);**//name=001,age=People@75412c2f**
map.put("002", p2);**//name=002,age=People@340f438e**
map.put("003", p3);**//name=003,age=People@30c7da1e**
Set<String>keys=map.keySet();
for(String key:keys) {
System.out.println("name="+key+",age="+map.get(key));
}
}
}
public class People {
String id;
int age;
public People(String id,int age ){
this.id =id;
this.age=age;
}
}
需要把People的輸出改為你要的數字
public class People {
String id;
int age;
public People(String id,int age ){
this.id =id;
this.age=age;
}
****
public String toString(){//多加上這個就可以了
return "ID"+id+"AGE"+age;
}
****
}
改完印出來就是你要的數字了
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MapTest {
public static void main(String[] args) {
People p1 = new People("001",21);
People p2 = new People("002",33);
People p3 = new People("003",41);
System.out.println(p1);**//ID001AGE21**
Map<String,People>map=new HashMap<>();
map.put("001", p1);**//name=001,age=ID001AGE21**
map.put("002", p2);**//name=002,age=ID002AGE33**
map.put("003", p3);**//name=003,age=ID003AGE41**
Set<String>keys=map.keySet();
for(String key:keys) {
System.out.println("name="+key+",age="+map.get(key));
}
}
}
參考資料
https://www.geeksforgeeks.org/comparator-interface-java/