class ListTest
{
int number;
String name;
ListTest(int number)
{
this.number=number;
}
ListTest(String name)
{
this.name=name;
}
public String hop()
{
return name+":"+number;
}
public static ListTest MYget(Object ob)
{
ListTest test=(ListTest)ob;
System.out.println(test.hop());
return test;
}
public static void main(String[] args)
{
Map m=new HashMap();
for(int i=0;i<5;i++)
{
m.put(new ListTest("ListTest"+i),new ListTest(i));
}
Set set=m.keySet();
Iterator it=set.iterator();
while(it.hasNext())
{
ListTest.MYget(m.get(it.next()));
}
}
}上面代码的输入结果是:
null:2
null:1
null:0
null:3
null:4
是什么原因啊,数字是乱的,字符串name是null,请各位朋友帮忙!结果应该是下面的这个呀:
ListTest0:0
ListTest1:1
ListTest2:2
ListTest3:3
ListTest4:4
m.put(new ListTest("ListTest"+i),new ListTest(i));
这句,key和value完全是2个对象么
当然没有name了
应该
m.put("ListTest"+i,new ListTest("ListTest"+i,i));
然后添加一个2个参数的构造方法
还有Set表是不会按顺序排的,如果要排序,需要用TreeSet,或SordedSet
ListTest(int number,String name)
this.number=number;
this.name=name;
}
把ListTest.MYget(m.get(it.next()));改成ListTest.MYget(it.next());会是另一种结果,即
ListTestX:0 //X是0-4,不一定按顺序,LZ好好体会一下保存在Map中的key和value对象有什么不同其次,Map是无序的,所以你不能保证一定按number从小到大的顺序输出,如果要按顺序,需要自己排序
m.put(new ListTest("ListTest" + i), new ListTest(i));你new了两个对象,一个为KEY一个为VALUE,而你在调用MYget方法时,只传递了Value进去,ListTest.MYget(m.get(it.next()));结果自然就只有value而没有KEY了。
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;public class ListTest {
private int number;
private String name; public ListTest(String name, int number) {
this.name = name;
this.number = number;
} public String toString() {
return name + ":" + number;
} public static ListTest convert(Object obj) {
if (obj instanceof ListTest) {
ListTest lt = (ListTest) obj;
return lt;
}
return null;
} public static void main(String[] args) {
Map m = new LinkedHashMap();// 這個會按照你插入的順序保存
for (int i = 0; i < 5; i++) {
m.put("ListTest" + i, new ListTest("ListTest" + i, i));
}
Set set = m.keySet();
Iterator it = set.iterator();
while (it.hasNext()) {
System.out.println(ListTest.convert(m.get(it.next())));
} // 另一種遍歷map的方式
for(Object obj : m.entrySet()){
Entry e = (Entry) obj;
System.out.println(e.getKey());
System.out.println(ListTest.convert(e.getValue()));
}
}
}