2015-09-23 42 views
-1
class A{ 
private static Map<String,String> map=new HashMap<String,String>(); 
public A() 
{ 
    map.put("micky","hello"); 
    map.put("micky","hey"); 
} 
public int size() 
{ 
    return map.size(); 
} 
public static void main(String[] args) 
{ 
    System.out.println(map.size()); 
} 

//爲什麼它給出0作爲答案。有人能解釋我嗎? }收集框架中的HashMap

+3

你認爲,爲什麼它不應該是0? – Seelenvirtuose

回答

2

您正在將構造函數中的元素添加到地圖中。但是你永遠不會調用構造函數。這就是原因。

當您安裝類A時,調用構造函數,您可以看到更改的大小。

public static void main(String[] args) 
{ 
    A a = new A(); //invokes constructor. 
    System.out.println(map.size()); // now prints size 
} 
+0

它不在其他包中工作,是嗎? – Andrew

+0

@AndrewTobilko這是另一回事。 Main與現在屬於同一班級。 –

1

您正在將類A的構造函數中的元素添加到地圖HashMap中。

您從不調用構造函數,因此您的地圖HashMap的大小爲0,因爲它必須是因爲地圖有0個元素。

這是相當奇怪的,你在做什麼有,但如果你想在HashMap中2項必須實例類A的元素

public static void main(String[] args) 
{ 
    // METHOD 1 
    var smth = new A(); 
    System.out.println(map.size()); // You will see the difference 

    // METHOD 2 
    System.out.println(new A().size()); //call constructor, add items, call the size method of class A 
} 
0

你應該調用類的構造函數添加任何地圖的價值之前打印的內容

0

您必須通過CLASSA refrence訪問size()方法:

System.out.println(A.map.size());

0

您沒有初始化默認構造函數,所以HashMap也沒有初始化。嘗試下面的代碼,它工作正常

import java.util.*; 
class A 
{ 
    private static Map<String,String> map=new HashMap<String,String>(); 
    public A() 
    { 
     map.put("micky","hello"); 
      map.put("micky","hey"); 
    } 
    public int size() 
    { 
      return map.size(); 
    } 


    public static void main(String[] args) 
    { 
     A a = new A(); 
     System.out.println(map.size()); 
    } 
}