Which is better / faster in Java: 2 method calls or 1 object call

I'm afraid this is a terribly stupid question. However, I can not find the answer to it and therefore I need some help :)

Let's start by simplifying my real problem:

Suppose I have a couple of boxes, each of which is filled with a mixture of different gems.

Now I create a gem object that has an attribute color and the getColour method to get the color of the gem. Next, I create an object window in which there is a list of gems as an attribute and the getGem method to get a gem from this list.

Now I want to count all the gems in all the boxes by color. Now I could do something like

int sapphire = 0;
int ruby = 0;
int emerald = 0;

for(each box = i)
    for(each gem = j)
        if(i.getGem(j).getColour().equals("blue")) sapphire++;
        else if(i.getGem(j).getColour().equals("red")) ruby++;
        else if(i.getGem(j).getColour().equals("green")) emerald++;

or i could do

int sapphire = 0;
int ruby = 0;
int emerald = 0;
String colour;

for(each box = i)
    for(each gem = j)
        colour = i.getGem(j).getColour();
        if(colour.equals("blue")) sapphire++;
        else if(colour.equals("red")) ruby++;
        else if(colour.equals("green")) emerald++;

, ? , , , "" ?

+4
3

:

int sapphire = 0;
int ruby = 0;
int emerald = 0;

for(each box = i) {
    for(each gem = j) {
        String colour = i.getGem(j).getColour();
        if("blue".equals(colour)) sapphire++;
        else if("red".equals(colour)) ruby++;
        else if("green".equals(colour)) emerald++;
    }
}
  • for. ? , , .
  • STATIC_STRING.equals(POSSIBLE_NULL_VALUE).

: . , . : .

+2

, : O (i * j). , 4 * O (i * j). ( O (i * j) ) O (i * (j + 2)). , , , .

+2

.

- (, enum). .

( Java, ).

 enum GemColour {
     blue,
     red,
     green
 }

count:

 Map<GemColour, Integer> counts = new EnumMap<GemColour, Integer>(GemColour.class);

 for (Box b: box) {
    for (Gem g: box.getGems() {
       Integer count = counts.get(g.getColour());
       if (count == null) { 
          count=1;
       } else {
          count+=1;
       }

       counts.put(g.getColour(), count);
    }
 }

, , - . , , , , ( - ).

, , :

counts.get(GemColour.blue);

, API- java Stream :

boxes.stream().map(Box::getGems).flatMap(Collection::stream).collect(groupingBy‌​‌​(Gem::getColour, counting()))

, , .

+1

All Articles