簡體   English   中英

在Java中填充Map的最有效方法

[英]Most efficient way to fill a Map in Java

我是Java新手,我正在編寫一個簡單的“正面報價”應用程序。 (使用Android Studio),您可以按一個按鈕,從地圖上顯示一個正面引用(隨機選擇)。

代碼本身很基本:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Sets the right TextView / Button to each object
        final TextView textView = (TextView)findViewById(R.id.textView);
        final Button button1 =  (Button)findViewById(R.id.button);

        // Implement listener for your button so that when you click the
        // button, android will listen to it.
        button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Map<Integer, String> quotes = new HashMap<Integer, String>();
                // Generate your quotes Map
                quotes = createQuotesMap();

                Random generator = new Random();
                Object[] values = quotes.values().toArray();
                Object randomValue = (String) values[generator.nextInt(values.length)];
                // Perform action on click
                textView.setText(randomValue.toString());
            }         });
    }

但我的問題來自我填寫報價地圖:

 public Map<Integer, String> createQuotesMap() {
        Map<Integer, String> quotes = new HashMap<Integer, String>();

        quotes.put(1, "Correction does much, but encouragement does more.");
        quotes.put(2, "Keep your face to the sunshine and you cannot see a shadow.");
        quotes.put(3, "Once you replace negative thoughts with positive ones, you'll start having positive results.");
        quotes.put(4, "Positive thinking will let you do everything better than negative thinking will.");
        quotes.put(5, "Pessimism leads to weakness, optimism to power.");
        quotes.put(6, "The thing that lies at the foundation of positive change, the way I see it, is service to a fellow human being.");
        quotes.put(7, "In every day, there are 1,440 minutes. That means we have 1,440 daily opportunities to make a positive impact.");
        quotes.put(8, "Attitude is a little thing that makes a big difference.");
        return quotes;
}

是否有更有效的方式來填充我的Map,或者更好的容器來填充這樣的基本應用程序? 你能否從我分享的代碼塊中指出糟糕的編碼習慣?

編輯:

我的應用。 現在已經完成了 - 我創建了一個引號數組(只有一次而不是像之前一樣每次點擊)並顯示一個隨機選擇的引號。

提示:這里的主要表現方面是:

  1. 您不希望為每個新用戶創建新地圖。 這些報價將一直是相同的,對吧; 所以一個和唯一值得擔心的是:如何確保您所創建的地圖一次。 因此,您可以創建一個靜態類范圍的映射,而不是使用局部變量。
  2. 你為什么想用地圖? 你知道,當你想要一系列的整體成為你的關鍵; 你為什么不用List?

換句話說:“優化”總是試着想一想大局。 但是你的問題意味着你正在從事物的另一面思考。 你花時間擔心單一操作的成本; 而不是在一個洞看你的應用程序......地圖與列表事情相同。 使用地圖絕對沒有意義......然后像列表一樣使用它。

首先,就效率而言,不是每次單擊按鈕時生成地圖,而是考慮將其設置為Activity的字段並在onCreate()啟動它。 然后,您可以在onClickListener使用該字段:

 //Class field
 private Map<Integer, String> quotes; 

 protected void onCreate(Bundle savedInstanceState) {

        // Generate your quotes Map 
        quotes = createQuotesMap();

        button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Random generator = new Random();
                Object[] values = quotes.values().toArray();
                //etc
            }         
        });
    }

其次,最重要的是,這確實不能保證使用Map 最好使用簡單數組或ArrayList

您仍然可以使用array[myRandomIndex]arrayList.get(myRandomIndex)從它們中訪問隨機元素,具體取決於您希望如何實現它。

請注意,初始化這些數組不應該在OnClickListener完成,因為每次單擊按鈕時它都會運行該代碼。

您可以使用createQuotes()方法創建一次數組。 而且您不需要地圖,因為您只需要在給定字符串中獲取隨機字符串。 至於地圖中的鍵,它可以完美地轉換為數組的索引。 所以我建議你使用以下內容:

public class YourClass {

    private static final String[] QUOTES = createQuotes();
    private Random generator = new Random();

    protected void onCreate(Bundle savedInstanceState) {
        // ...
        button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String randomValue = QUOTES[generator.nextInt(QUOTES.length)];
                textView.setText(randomValue);
            }         
        });
    }

    private static String[] createQuotes() {
        String[] quotes = new String[] {
                "Correction does much, but encouragement does more.",
                "Keep your face to the sunshine and you cannot see a shadow.",
                "Once you replace negative thoughts with positive ones, you'll start having positive results.",
                "Positive thinking will let you do everything better than negative thinking will.",
                "Pessimism leads to weakness, optimism to power.",
                "The thing that lies at the foundation of positive change, the way I see it, is service to a fellow human being.",
                "In every day, there are 1,440 minutes. That means we have 1,440 daily opportunities to make a positive impact.",
                "Attitude is a little thing that makes a big difference."
        }
        return quotes;
    }
}

我無法測試代碼。 如果有任何錯誤,請編輯我。

String[] quotes = {
"Correction does much, but encouragement does more.",
"Keep your face to the sunshine and you cannot see a shadow.",
"Once you replace negative thoughts with positive ones, you'll start having positive results.",

};

public void onClick(View v){

    ...

    Random r = new Random();
    selectedQuote = r.nextInt(quotes.length);
    textView.setText(selectedQuite);
    ...

}

我希望這可以幫助你解決問題

String[] stringQuotes = {
"Correction does much, but encouragement does more.",
"Keep your face to the sunshine and you cannot see a shadow.",
"Once you replace negative thoughts with positive ones, you'll start having positive results.",
"Positive thinking will let you do everything better than negative thinking will."
};

for(int i = 0; i < stringQuotes.length; i++){
    quotes.put(i, stringQuotes[i]);
}

使用for循環更快,但它要求所有字符串都保存在string []數組中,這使得初始化更快

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM