Showing posts with label java_8. Show all posts
Showing posts with label java_8. Show all posts
Monday, January 30, 2017

Java recipe: Initialize an ArrayList with zeros

It's often useful to have a list filled with zeros of the specified length N.
Why would you want one? Well, it's handy during the work with algorithms, or just to avoid null checks.
Usually, instead of the List filled with 0s an Array is enough: new int[N]
- creates an array of N integers with zero value.
new ArrayList(N) (has the size 0) is NOT the same as new int[N] (has the length N)

- The integer passed to the constructor of list represents its initial capacity (the number of elements it can hold before it needs to resize its internal array) which has nothing to do with the initial number of elements in it.
Whatever, below are the bunch of ways to create the List filled with zeros, if you need one.
In each example we will create a list filled with 100 zeros. (Java8 implementation with StreamAPI included).
Wednesday, November 5, 2014

Interface vs Abstract class in Java 8

Difference between Interface and Abstract class in Common

In Java you can extend only one class (because the Diamond of Death), whether or not it is abstract, whereas you can implement any number of interfaces.

In interfaces, all fields are public, static, and final, and all declared methods are public.
In abstract classes, you can declare concrete fields and methods with any existing access modifiers. 
So, an Interface is about public API.
The contract that has to be followed during the implementation.
It means that all implementation objects are guaranteed to provide the functionality declared in interface.
But an Abstract class is about Common implementation.
The basic design that has to be expanded or reused.
It means that all objects that extend an abstract class have to implement
their specifics(missing pieces
) to became some kind of concrete entity.
Based on above, we also can say, that Interfaces supposed to combine not related entities with similar abilities, whereas Abstract classes supposed to share common stuff among the several kinds of the same entity.