我是 Java 新手,正在编写一个简单的“正面引语”应用程序。 (使用 Android Studio)让您按下一个按钮,它会显示来自 map 的正引号(随机选择)。
代码本身相当基础:
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 ,或者有更好的容器来填充这样的基本应用程序?您能否从我分享的代码块中指出不良的编码习惯?
编辑:
我的应用程序。现在完成了 - 我创建了一个引号数组(只创建一次,而不是像以前那样每次点击都创建)并显示一个随机选择的引号。
最佳答案
提示:这里的主要性能方面是:
- 您不想为每个新用户创建新 map 。报价一直都是一样的,对吧;因此,一个也是唯一值得担心的事情是:如何确保只创建一次 map 。因此,您可以创建一个静态类范围映射,而不是使用局部变量。
- 为什么要使用 map ?你知道,当你想要一个整数序列作为你的键时;你为什么不只使用一个列表?
换句话说:在“优化”时,请始终尝试着眼大局。但是你的问题暗示你非常从事物的另一面思考。你把时间花在担心单次手术的成本上;而不是在一个洞里看你的应用程序...... map 与列表的事情是一样的。使用 map 绝对没有意义......然后像列表一样使用它。
关于java - 用 Java 填充 map 的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38202444/