Christopher K. Christopher K. - 5 months ago 29
Android Question

Most efficient way to fill a Map in Java

I am new to Java and I'm coding a simple "Positive Quotes" app. (using Android Studio) that lets you press on a button, that will display a positive quote (randomly selected) from a Map.

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? Could you also point out bad coding habits from the chunk of code that I have shared?

Thank you !

Answer

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(). You can then use that field in your onClickListener as such:

 //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. You are better off using a simple array or an 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.

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.

Comments