2011-07-21 53 views
-1

我寫了以下兩個函數 我想用HashMap實現函數(代替函數) 怎麼做?JAVA +創建HashMap來代替函數

static void someFunction(int count, int[] anArray) 
{  
    for (int i=0;i<anArray[count];i = i + 1) 
    { 
    System.out.print("#"); 
    } 
    System.out.println(""); 
} 

static void someFunctionB(int[] anArray , int count, String stringfinal, String sttr) 
{  
    anArray[count]= stringfinal.replaceAll("[^"+sttr+"]", "").length(); 
} 

someFunctionB(anArray , count, stringfinal, sttr );   

someFunction(count, anArray); 
+0

爲什麼我得到投票-1,?我只在3天前開始學習Java, - :( – david

回答

0

不使用任何功能(除了public static void main(String[] args)),你可以這樣做:

Map<Integer, Integer> mapThatPretendsToBeAnArray = new LinkedHashMap<Integer, Integer>(); 
mapThatPretendsToBeAnArray.put(0, 17); 
mapThatPretendsToBeAnArray.put(1, 5); 
mapThatPretendsToBeAnArray.put(2, 1); 
mapThatPretendsToBeAnArray.put(3, 319); 

//someFunction() 
for (int i = 0; i < mapThatPretendsToBeAnArray.get(1); i++) { 
    System.out.print("#"); 
} 
System.out.println(""); 

//someFunctionB() 
mapThatPretendsToBeAnArray.put(3, "stringFinal".replaceAll("[^"+"sttr"+"]", "").length()); 

但當然,someFunction()someFunctionB()更加有用,因爲他們讓你參數的參數,而不是在這個例子中必須選擇硬編碼的。

+0

爲什麼mapThatPretendsToBeAnArray.get(1);(get 1?) – david

+0

@david - 這是任意的,爲了舉例。 'count'參數在'someFunction()'內部完成,它只是數組/地圖的索引/鍵。爲什麼不使用'List'而不是'Map'呢? – aroth

+0

mapThatPretendsToBeAnArray.put(0,17) ; mean stringFinal = 0 and sttr = 17? – david

0

請記住,一個Map是一個Key-Value數據結構 - 例如,您可能會使用一個字符串或其他更有意義的標識符。此外,儘管在這種情況下行爲表面上是相同的,但實際上你正在做一些非常不同的事情。

使用您的API:

import java.util.Map; 
import java.util.HashMap; 

public class CounterHelper { 

    static int key = 6; 

    public static void main(String[] args) { 
    Map<Integer, Integer> hashMap = new HashMap<Integer, Integer>(); 
    someFunctionB(hashMap, key, "[^toRemove] remaining", "toRemove"); 
    someFunction(key, hashMap); 
    } 

    public static void someFunction(int key, Map<Integer, Integer> hashMap) {  
    for (int i=0; i < hashMap.get(key); i++) { 
     System.out.print("#"); 
    } 
    System.out.println(""); 
    } 

    public static void someFunctionB(Map<Integer, Integer> hashMap, int key, String stringfinal, String sttr) { 
    hashMap.put(key, stringfinal.replaceAll("[^"+sttr+"]", "").length()); 
    } 

} 

只是用地圖:

public class CounterHelper { 

    static int value = 4; 
    static int key = 6; 

    public static void main(String[] args) { 
     java.util.Map<Integer, Integer> hashMap = new java.util.HashMap<Integer, Integer>(); 
     hashMap.put(key, value); 

     int hashes = hashMap.get(key); 
     for (int i = 0; i < hashes; i++) { 
      System.out.println("#"); 
     } 
    } 

    }