2011-07-21 12 views
-1

私は以下の2つの関数を書いています (関数の代わりに)HashMapで関数を実装したいですか? これを行う方法は? 、あなたのような何かを行うことができます(public static void main(String[] args)から離れて)すべての機能を使用せずにJAEA +関数の代わりに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

をあなたのAPIを使用して

?私は3日前にJavaを学び始めるだけです: - :( – david

答えて

0

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);(1を得る) – david

+0

@david - それは、例のために任意です。 'count'パラメータは' someFunction() 'の中で配列/マップのインデックス/キーです。また、' Map'の代わりに 'List'を使うのはなぜですか? – aroth

+0

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

0

MapはKey-Valueデータ構造であることに注意してください。たとえば、文字列やその他の意味のあるキーの識別子を使用できます。また、この例では動作は表面的には同じですが、実際にはまったく異なる動作を行っています。

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()); 
    } 

} 

をジャスト地図使って:私は投票-1を取得する理由

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("#"); 
     } 
    } 

    } 
関連する問題