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

时间:2016-07-05 11:35:31

标签: java android

我是Java新手,我正在编写一个简单的#34;正面报价"应用程序。 (使用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,或者更好的容器来填充这样的基本应用程序?您是否也可以从我分享的代码块中指出错误的编码习惯?

编辑:

我的应用。现在已经完成了 - 我创建了一个引号数组(只有一次而不是像之前一样每次点击)并显示一个,随机选择。

5 个答案:

答案 0 :(得分:3)

提示:这里的主要表现方面是:

  1. 您不希望为每个新用户创建新地图。这些报价将一直是相同的,对吧;所以一个,唯一值得担心的是:如何确保您只创建一次地图。因此,您可以创建一个静态类范围的映射,而不是使用局部变量。
  2. 你为什么要使用地图?你知道,当你想要一系列的整体成为你的关键;你为什么不用List?
  3. 换句话说:“优化”总是试着想一想大局。但是你的问题意味着你正在从事物的另一面思考。你花时间担心单一操作的成本;而不是在一个洞看你的应用...... 地图与列表相同的事情。使用地图绝对没有意义......然后像列表一样使用它。

答案 1 :(得分:2)

首先,在效率方面,不要在每次点击按钮时生成地图,而应考虑将其设为活动字段并在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中完成,因为每次单击按钮时都会运行该代码。

答案 2 :(得分:1)

您可以使用方法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;
    }
}

我无法测试代码。如果有任何错误,请编辑我。

答案 3 :(得分:1)

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);
    ...

}

我希望这可以帮助您解决问题

答案 4 :(得分:0)

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 []数组中,这使得初始化更快