Вы просматриваете старую версию данной страницы. Смотрите текущую версию.

Сравнить с текущим просмотр истории страницы

« Предыдущий Версия 20 Текущий »

Структура JVM

Структура памяти

В документации полностью описаны области памяти в JVM - https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html

Сборщик мусора

Документация по GC - https://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html

Примеры

static char[] alphabet;

static {
    alphabet = new char[26];
    for (char c = 'a'; c <= 'z'; c++) {
        alphabet[c - 'a'] = c;
    }
}


public static void main(String ... args) {
    while(true) {
        String word = "";
        for (int i = 0; i < 1000; i++) {
            word += alphabet[(int)(Math.random()*26)];
        }
        System.out.println("word = " + word);
    }
}


private static recurrent(int i) {
    recurrent(++i);
}


Строки

Интернирование

Пример интернирования
String s1 = "Hello, World";
String s2 = "Hello, World";
System.out.println("Comparing s1 and s2");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));

System.out.println("Comparing s1 and s3");
String s3 = new String(s1);
System.out.println(s1 == s3);
System.out.println(s1.equals(s3));

System.out.println("Interning s1 and s3");
System.out.println(s1 == s3.intern());

System.out.println("Comparing concatenated strings");
String s4 = s1+"!";
System.out.println(s4 == s1+"!");
System.out.println(s4 == (s1+"!").intern());
System.out.println(s4.intern() == (s1+"!").intern());
System.out.println(s4.equals(s1+"!"));

Полезные ссылки

    1. String pooling - http://java-performance.info/string-intern-in-java-6-7-8/


Методы

Примеры работы со строками
String description = "The class String includes methods for examining\n" +
        " * individual characters of the sequence, for comparing strings, for\n" +
        " * searching strings, for extracting substrings, and for creating a\n" +
        " * copy of a string with all characters translated to uppercase or to\n" +
        " * lowercase";

System.out.println("Length: "+description.length()+", is empty: "+description.isEmpty());

String[] words = description.split(" ");
for(String word : words) {
    System.out.println(word);
}

String shortDescription =  description.substring(10);
System.out.println(shortDescription);
shortDescription =  description.substring(description.indexOf("String"));
System.out.println(shortDescription);

String usdNumber = "$101.78";
System.out.println(usdNumber.matches("\\$\\d*\\.\\d*"));

String stringWithPrice = "Cost is 101.56 USD in Target";
System.out.println(stringWithPrice.replaceAll("(\\d*\\.\\d*)( USD)", "\\$$1"));

String[] numbers = new String[] {"one", "two", "three"};
System.out.println(String.join(",", numbers));


StringBuilder  и StringBuffer

Пример использования StringBuilder
//плохо
String result = "0";
for (int i = 1; i < 10000; i++) {
    result += "," + i;
}
System.out.println(result);


//хорошо
StringBuilder sb = new StringBuilder("0");
for (int i = 0; i < 10000; i++) {
    sb.append(",").append(i);
}
System.out.println(sb.toString());


Числа

double d = 0.1;
double result = 0.0;
for (int i = 0; i < 10; i++) {
    result += d;
}

System.out.println("result = " + result);


BigDecimal bc = new BigDecimal(0.1, new MathContext(10, RoundingMode.DOWN));
BigDecimal result = new BigDecimal(0.0, new MathContext(10, RoundingMode.DOWN));
for (int i = 0; i < 10; i++) {
    result = result.add(bc);
}

System.out.println("result = " + result);


Currency

Currency usd = Currency.getInstance("USD");
Currency eur = Currency.getInstance("EUR");
Currency gbp = Currency.getInstance("GBP");
System.out.println("usd = " + usd);
System.out.println("eur = " + eur);
System.out.println("gbp = " + gbp);

System.out.println(usd.getDisplayName());
System.out.println(usd.getDefaultFractionDigits());


Задачи

CurrencyExchenge

Необходимо реализовать класс Money с поддержкой валют и методами add, subtract, multiply, devide

Постановка: CurrencyExchange.zip

Quantity

Необходимо реализовать класс Quantity с поддержкой единиц измерения и арифметических операций: add, subtract, multiply, divide

Проект: Quantity.zip

Материалы

Презентация: Типы данных в Java


  • Нет меток