简体   繁体   English

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

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

I am new to Java and I'm coding a simple "Positive Quotes" app. 我是Java新手,我正在编写一个简单的“正面报价”应用程序。 (using Android Studio) that lets you press on a button, that will display a positive quote (randomly selected) from a Map. (使用Android Studio),您可以按一个按钮,从地图上显示一个正面引用(随机选择)。

The code itself is rather basic: 代码本身很基本:

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

But my question comes from where I fill up my quotes map: 但我的问题来自我填写报价地图:

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

Would there be a more efficient way of filling up my Map, or a better container for such a basic application? 是否有更有效的方式来填充我的Map,或者更好的容器来填充这样的基本应用程序? Could you also point out bad coding habits from the chunk of code that I have shared? 你能否从我分享的代码块中指出糟糕的编码习惯?

EDIT: 编辑:

My app. 我的应用。 is now complete - I create an array of quotes (only once and not at every click like before) and display one, randomly chosen. 现在已经完成了 - 我创建了一个引号数组(只有一次而不是像之前一样每次点击)并显示一个随机选择的引号。

Hint: the main performance aspects here are: 提示:这里的主要表现方面是:

  1. You do not want to create a new map for each new users. 您不希望为每个新用户创建新地图。 The quotes will be be the same all the time, right; 这些报价将一直是相同的,对吧; so the one and only thing worth worrying about is: how to make sure that you create the map exactly once. 所以一个和唯一值得担心的是:如何确保您所创建的地图一次。 So instead of using a local variable, you could create a single static class-wide map. 因此,您可以创建一个静态类范围的映射,而不是使用局部变量。
  2. Why do you want to use a map? 你为什么想用地图? You know, when you want to have a sequence of ints to be your key; 你知道,当你想要一系列的整体成为你的关键; why don't you just use an List? 你为什么不用List?

In other words: when "optimizing" always try think about the big picture. 换句话说:“优化”总是试着想一想大局。 But your question implies that you are very much thinking from the opposite side of things. 但是你的问题意味着你正在从事物的另一面思考。 You spent your time worrying about the cost of a single operation; 你花时间担心单一操作的成本; instead of looking at your application at a hole ... Same thing for the map versus list thing. 而不是在一个洞看你的应用程序......地图与列表事情相同。 There is absolutely no point in using a map ... to then use it like an list. 使用地图绝对没有意义......然后像列表一样使用它。

Firstly, in terms of efficiency, instead of generating the map every time you click the button, consider making it a field of your Activity and initiating it in your onCreate() . 首先,就效率而言,不是每次单击按钮时生成地图,而是考虑将其设置为Activity的字段并在onCreate()启动它。 You can then use that field in your onClickListener as such: 然后,您可以在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
            }         
        });
    }

Secondly and most importantly, this really doesn't warrant the use of a Map . 其次,最重要的是,这确实不能保证使用Map You are better off using a simple array or an ArrayList . 最好使用简单数组或ArrayList

You can still access random elements from them by using array[myRandomIndex] or arrayList.get(myRandomIndex) depending on how you wish to implement it. 您仍然可以使用array[myRandomIndex]arrayList.get(myRandomIndex)从它们中访问随机元素,具体取决于您希望如何实现它。

Just be mindful that initialising these arrays should not be done in an OnClickListener as it would run that code every time the button is clicked. 请注意,初始化这些数组不应该在OnClickListener完成,因为每次单击按钮时它都会运行该代码。

You can create an array once using the method createQuotes() . 您可以使用createQuotes()方法创建一次数组。 And you don't need a map, because you only need to obtain a random string among the given strings. 而且您不需要地图,因为您只需要在给定字符串中获取随机字符串。 As for the key in the map, it transforms perfectly into the array's index. 至于地图中的键,它可以完美地转换为数组的索引。 So I suggest you use the below : 所以我建议你使用以下内容:

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

I can't test the code. 我无法测试代码。 Please edit me if there's any error. 如果有任何错误,请编辑我。

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

}

I hope this helps you solve yout problem 我希望这可以帮助你解决问题

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

It is faster to use a for-loop, but it requires that all strings are saved in a string[] array which makes the initialization faster 使用for循环更快,但它要求所有字符串都保存在string []数组中,这使得初始化更快

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM