The Developer Times — simplicity & usability

About
В течения дня разрабатываю коммерческие Ruby on Rails, Java и C# web-приложения. Вечером исследую технологии разработки ПО, пишу заметки в блог и иногда могу забить гвоздь. :) По возможности, стараюсь делать проще и удобнее. Для Tumblr поддерживаю тему "Flashback to Simplicity". А связаться со мной можно через местный телеграф.

Самый короткий способ избавиться от дубликатов в списке в Java

Избавиться от дубликатов в списке и при этом не потерять порядок.

// Список с дубликатами
ArrayList list = new ArrayList() {{ add("A"); add("B"); add("A"); }};

// Список без дубликатов
list = new ArrayList(new LinkedHashSet(list));

Возможно эффективность страдает, зато коротко. Как вариант, можно использовать org.apache.commons.collections.list.SetUniqueList.

List uniqueList = SetUniqueList.decorate(new ArrayList());

Если в списке хранятся нестандартные объекты, будет также полезно переопределить public boolean equals(Object obj) и public int hashCode() при помощи org.apache.commons.lang3.builder.EqualsBuilder и org.apache.commons.lang3.builder.HashCodeBuilder соответственно.

| tags:

Копирование InputStream в OutputStream одной строчкой

Вы всё ещё пишете так:

// InputStream is
// OutputStream op;
byte[] buf = new byte[4096];
int len;
while ((len = is.read(buf)) != -1) {
  op.write(buf, 0, len);
}
op.flush();
is.close();

Зачем? Ведь можно писать короче и проще, используя IOUtils:

// InputStream is
// OutputStream op;
IOUtils.copy(is, os);
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
| 1 заметка | tags:

Instance initializer (double brace initialization)

Есть такая замечательная конструкция в Java — instance initializer:

User u = new User() {{
  email = "test@email.com";
  password = "password";
}};

The first brace creates a new anonymous inner class, the second declares an instance initializer block that is run when the anonymous inner class is instantiated. This type of initializer block is formally called an “instance initializer”, because it is declared within the instance scope of the class — “static initializers” are a related concept where the keyword static is placed before the brace that starts the block, and which is executed at the class level as soon as the classloader completes loading the class. The initializer block can use any methods, fields and final variables available in the containing scope, but one has to be wary of the fact that initializers are run before constructors (but not before superclass constructors).

Но,

This only works only for non-final classes because it creates an anonymous subclass.

Удобно.

(Источник: c2.com)

| tags: