1. java判断两个字符串是否相等用equals
2. java只传递指针遇到的坑:
1 import java.util.*;
2
3 public class mapTest {
4 public static class EntryWeight{
5 public int entryid;
6 public float wordweight;
7 public int getentryid(){return entryid;}
8 public float getwordweigth(){return wordweight;}
9 public String toString() {
10 return "id=" + entryid + ", weight=" + wordweight;
11 }
12 }
13 public static void main(String[] args) {
14 ArrayList<EntryWeight> entryPairs = new ArrayList<EntryWeight>(5);
15 for(int i=0;i<5;i++){
16 EntryWeight entryPair = new EntryWeight();
17 entryPair.entryid = i;
18 entryPair.wordweight = (float)0.5+i;
19 entryPairs.add(entryPair);
20 System.out.println("entry pair: " + entryPair.getentryid() );
21
22 }
23 for(int i=0;i<entryPairs.size();i++){
24 System.out.println("entrys "+i+" : " + entryPairs.get(i).entryid );
25 }
26 for(int i=0;i<entryPairs.size();i++){
27 System.out.println("entrys "+i+" : " + entryPairs.get(i).wordweight );
28 }
29 for (Iterator<EntryWeight> iterator = entryPairs.iterator(); iterator.hasNext(); ) {
30 System.out.println(iterator.next());
31 }
32 }
33 }
这样写是正确的,输出:
entry pair: 0
entry pair: 1
entry pair: 2
entry pair: 3
entry pair: 4
entrys 0 : 0
entrys 1 : 1
entrys 2 : 2
entrys 3 : 3
entrys 4 : 4
entrys 0 : 0.5
entrys 1 : 1.5
entrys 2 : 2.5
entrys 3 : 3.5
entrys 4 : 4.5
id=0, weight=0.5
id=1, weight=1.5
id=2, weight=2.5
id=3, weight=3.5
id=4, weight=4.5
把EntryWeight entryPair = new EntryWeight()放在for循环外边,其他都不改,
public static void main(String[] args) {
ArrayList<EntryWeight> entryPairs = new ArrayList<EntryWeight>(5);
EntryWeight entryPair = new EntryWeight();
for(int i=0;i<5;i++){
entryPair.entryid = i;
entryPair.wordweight = (float)0.5+i;
entryPairs.add(entryPair);
System.out.println("entry pair: " + entryPair.getentryid() );
}
输出变成了这样:
entry pair: 0
entry pair: 1
entry pair: 2
entry pair: 3
entry pair: 4
entrys 0 : 4
entrys 1 : 4
entrys 2 : 4
entrys 3 : 4
entrys 4 : 4
entrys 0 : 4.5
entrys 1 : 4.5
entrys 2 : 4.5
entrys 3 : 4.5
entrys 4 : 4.5
id=4, weight=4.5
id=4, weight=4.5
id=4, weight=4.5
id=4, weight=4.5
id=4, weight=4.5
是因为entryPairs.add()只是把地址传过来了,并没有新建一个entryPair,想起早晨师兄还说到这个,这么快就踩到了。
Java中集合提供的拷贝构造函数只支持浅拷贝而不是深拷贝,这意味着存储在原有List和克隆List中的对象会保持一致,并指向Java堆中同一内存地址。
2. map的key如果用数字的话可以定义成:
Map<Integer, EntryWeight> db = new HashMap<Integer, EntryWeight>(); db.put(0, entryList);