среда, 15 января 2014 г.

Java String Array Example

Это простой пример как обявить и проинициализировать массив(Array) в Java.

Итак, создадим JavaStringArrayExample.java класс с кодом:

package com.androidnn.javabasics.stringarray;
public class JavaStringArrayExample 
{
   public static void main(String args[]) 
   {
      // declare a string array with initial size
      String[] schoolbag = new String[4];
   
      // add elements to the array
      schoolbag[0] = "Books";
      schoolbag[1] = "Pens";
      schoolbag[2] = "Pencils";
      schoolbag[3] = "Notebooks";
   
      // this will cause ArrayIndexOutOfBoundsException
      // schoolbag[4] = "Notebooks";
   
      // declare a string array with no initial size
      // String[] schoolbag;
   
      // declare string array and initialize with values in one step
      String[] schoolbag2 = { "Books", "Pens", "Pencils", "Notebooks" };
   
      // print the third element of the string array
      System.out.println("The third element is: " + schoolbag2[2]);
   
      // iterate all the elements of the array
      int size = schoolbag2.length;
      System.out.println("The size of array is: " + size);
      for (int i = 0; i < size; i++) 
      {
         System.out.println("Index[" + i + "] = " + schoolbag2[i]);
      }
   
      // iteration provided by Java 5 or later
      for (String str : schoolbag2) 
      {
         System.out.println(str);
      }
   }
}

Explanation :
Есть 3 способа для объявления массивов :

  • String[] schoolbag = new String[4];
  • String[] schoolbag;  
  • String[] schoolbag2 = { "Books", "Pens", "Pencils", "Notebooks" };

В первом случае мы создаем массив используя "количество элементов".
Во втором случае мы просто объявлением переменную "Массив". Но, перед использованием мы обязаные его проинициализировать (schoolbag = new String[4]).
В третем же случае, мы перечислям все значения переменных. Размер же будет автоматически подсчитан.

Хотелось бы сразу подметить, Array в Java всегда имеет фиксированный размер. В том случае, если мы будем пытаться записать значение в несуществующую ячеку мы получим ArrayIndexOutOfBoundsException

Если же вам нужен массив с динамически изменяемым количеством ячеек, используйте ArrayList

Для прохода по элементам массива используется for в двух эпостасиях :) Последние 2 блока кода в примере.

Output

The third element is: Pencils
The size of array is: 4
Index[0] = Books
Index[1] = Pens
Index[2] = Pencils
Index[3] = Notebooks
Books
Pens
Pencils

Notebooks


воскресенье, 5 января 2014 г.

Only try optimization when you have knowledge of the actual bottleneck

I have seen architects who spend great effort on:

  • Fine-tuning logging statements
  • Replacing Vectors in legacy code
  • Replacing + operators with StringBuffers in loops
  • Refactoring existing, stable, mature and bug-free code for the sake of “performance”
  • …and other fancy stuff

Sadly, this is done without actually measuring what effect these efforts might have. Even if the application runs a bit faster, most of the times there are other more serious problems (like database locking, memory leaks, streams that are never closed/flushed) that nobody pays attention to.

Spending time to fix logging and gain 3% in speed is not very helpful when fixing the SQL queries would give 200% gains in speed.

Therefore, it’s important to keep in mind that any change that happens for performance reasons is actually a four-step process:
  1. Measure the current system (valid benchmarks are a big task on their own)
  2. Apply the change
  3. Measure again
  4. Evaluate the effort given and the performance gained ratio.

Remember the mantra for optimizations – measure, don’t guess.