terça-feira, 2 de agosto de 2016

Novidades Java9


Depois dos métodos de extensão para interfaces, das expressões lambda, das operações em massa para coleções e da nova API para Data e Hora, dentre várias outras adições e melhorias da versão 8, o que esperar da próxima versão?


Novidades da Versão 9


A lista de novas features pretendidas para a versão 9 é razoavelmente ambiciosa. Citando apenas as JEP (JDK Enhancement Proposal) mais significativas temos:


  • jshell: The Java Shell (Read-Eval-Print Loop) [JEP 222]
  • Microbenchmark Suite [JEP 230]
  • Novo cliente para HTTP 2 [JEP 110]
  • Suporte para Unicode 7.0 e 8.0 [JEP 227 & 267]
  • Atualização da Process e da Concurrency API [JEP 102 & 266]
  • Coletor de lixo G1 como default [JEP 248]
  • Modularização do código fonte e da biblioteca run-time [JEP 201 & 220]


Com isso, o Java 9 trará o novo console jshell que permitirá testar, sem necessidade de construção de um programa completo, comandos e expressões diretamente, o que se denomina REPL (read-evaluate-print-loop). O jshell  já está disponível na versão de testes (ainda incompleta) do JDK9.
A pequena suite para microbenchmark facilitará, e muito, a construção e realização de testes de desempenho e análises comparativas com o código Java. Com isso vai ser possivel determinar quais otimizações são realmente necessárias, sem necessitar de ferramentas externas de profiling.


Read-Eval-Print-Loop (REPL)


Se você já programa em linguagens como Scala, Ruby, Swift e JavaScript entre tantas outras, possivelmente já brincou com algum tipo de REPL. Essa ferramenta nada mais é do que um ambiente simples e interativo onde você pode facilmente executar códigos, oferecendo uma forma bastante efetiva de experimentar novos recursos e APIs.


Feedback para todas as suas ações


int valor = 100;
|  Added variable valor of type int with initial value 100


Você pode desativá-lo com o comando /feedback off. Digite /feedback e pressione o tab pra ver as demais opções. Não deixe de usar o tab (autocomplete) sempre que for usar um comando novo pra ver todas as suas possibilidades.


Com ou sem ponto e vírgula?


Sabe o ponto e vírgula clássico do final da linha? No REPL é opcional.





O release final deverá acontecer apenas em março de 2017!


Fonte:











quarta-feira, 22 de junho de 2016

Understanding Collections


I will quickly explain with an example each collection..
LIST: Is an ordered Collection (sometimes called a sequence). Lists may contain duplicate elements. Elements can be inserted or accessed by their position in the list, using a zero-based index.
  • ArrayList
    • Advantage: Search. One more advantage is that it is more flexible changing the underlying implementation of an ArrayList, for eg, if you want to make it synchronized, you can convert to a Vector without having to rewrite all the code for an Array.
    • Disadvantage: Insert and Delete. ArrayList has a performance limitation.  It allocates a particular amount of space... the "capacity".  Once you expand the ArrayList to exceed that capacity, the ArrayList has to copy the current array into new memory space, which has a performance hit.



  • LinkedList
    • Advantage: Insert and Delete. Faster Access time,can be expanded in constant time without memory overhead
    • Disadvantage: Search. If using doubly linked list then though it becomes easier to traverse from end but still it increases again storage space for back pointer.


















  • Vector
    • Advantage: Vector is synchronized which means it is suitable for thread-safe operations
    • Disadvantage: Poor performance when used in multi-thread environment



SET: Is a Collection that cannot contain duplicate elements. There are three main implementations. Not thread-safe
  • HashSet
    • Advantage: Insert and SearchOne more advantage is that it operates in constant time, as opposed to the O(log N) time for the Set class.
    • Disadvantage: Is that iterators return the values in a seemingly random order.


  • LinkedHashSet
    • Advantage: Elements gets sorted in the same sequence in which they have been added to the Set.
    • Disadvantage: Iteration performance

  • TreeSet
    • Advantage: Elements gets sorted in the same sequence in which they have been added to the Set.
    • Disadvantage: If you don’t supply a Comparator to define the ordering you want, TreeSet requires a Comparable implementation on the item class to define the natural order


MAP: Is an object that maps keys to values. A map cannot contain duplicate keys. There are three main implementations of Map interfaces
  • HashMap
    • Advantage: Used for storing Key & value pairs. permits nulls(null values and null key)
    • Disadvantage: There's also the potential for collisions. The cost of writing and/or executing the hashing-function could be high if the requirement for collision avoidance is strict, or if you have a small hash-space.


  • TreeMap
    • Advantage: Is that it allows to store the key-value mappings in a sorted order. Treemap internally uses red black tree.
    • Disadvantage: No guarantees concerning the order of iteration.


  • LinkedHashMap
    • Advantage: Allows predictable iteration order
    • Disadvantage: Memory usage and probably higher insertion cost


Conclusion

Whatever the application you are working, always try to use the best possible approach. There are different types of collections for use in differente situations, so do not hesitate. Think of the approach and choose the best possible option.

GitHub: https://github.com/mateusmachado/PocCollectionsJava