[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 95
  • Last Modified:

word0 challenge

Hi,

I am working on below challenge.
http://codingbat.com/prob/p152303

public Map<String, Integer> word0(String[] strings) {
  int len=strings.length;
   Map<String, Integer> map = new HashMap<String, Integer>();
 for(int i=0;i<len;i++){
   
 map.put(strings[i],0);
 }
  return map;
}

Open in new window


i passed all tests. any improvements or alternate approaches? please advise
0
gudii9
Asked:
gudii9
  • 2
  • 2
2 Solutions
 
ste5anSenior DeveloperCommented:
No need for an extra variable:

public Map<String, Integer> word0(String[] strings) {
  Map<String, Integer> result = new HashMap<String, Integer>();
  for (int count = 0; count < strings.length; count++) 
  {
      result.put(strings[count], 0);
  }
  
  return result;
}

Open in new window

0
 
zzynxSoftware engineerCommented:
Pretty straightforward.
No real improvements.
You could write your loop also as

for (String s : strings) {
    map.put(s, 0);
}

Open in new window

0
 
zzynxSoftware engineerCommented:
>> No need for an extra variable
I don't know.
Without that variable, for each iteration of the loop you'll evaluate
strings.length
If you store that value in a variable, you only determine the length once.

(But I guess compiler optimalisation will do that for you)
0
 
ste5anSenior DeveloperCommented:
(But I guess compiler optimalisation will do that for you)

Yup, in both cases.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now