This is a basic coding style question as I'm trying to be super accurate on best practices. I've browsed around and pieced together some Java code for generating a random string from a list and adding it to an existing string in my Android App.
On investigation I found two approaches, one was to use a single line of code to generate the random string by selecting an item from a list, another was to call a routine to do basically the same thing. I know it can be good to break the code up into smaller chunks, but in this case would one method be generally preferred over the other? Note that the first option is commented out in the code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
//Add a random day to the string
List<String> list = new ArrayList<>();
list.add("Monday");
list.add("Tuesday");
list.add("Wednesday");
list.add("Thursday");
list.add("Friday");
list.add("Saturday");
list.add("Saturday");
//Random rand = new Random();
//String random = list.get(rand.nextInt(list.size()));
String random = getRandom(list);
message += " " + random;
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
static public <T> T getRandom(List<T> list){
Random rand = new Random();
if(list == null || list.isEmpty()){
return null;
}else{
return list.get(rand.nextInt(list.size()));
}
}
Aucun commentaire:
Enregistrer un commentaire