Why does my static block allows to call parent class static method without using parentclass reference?

From what I understand, usually the static method should be called using class’s reference or it can be called directly without reference if its in a static method or static block.

But does this apply when static method is called from child class static blocks?

Why it allows such thing, as static methods are not inherited, it should only be allowed using parent class name right?

public abstract class abs {

    /**
     * @param args
     */
    abstract void m();
    static void n(){
        System.out.println("satic method");
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}
class myclass extends abs{

    @Override
    void m() {
        // TODO Auto-generated method stub

    }
    static{
        n();
    }
}

Why my child class static block can call parent class static method without reference or classname?

Solution:

Static method n() is inherited by subclass myclass, so you can call it directly in the static block of myclass.

Else clause in lambda expression

I use the following lambda expression to iterate over PDF files.

public static void run(String arg) {

        Path rootDir = Paths.get(arg);
        PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:**.pdf");
        Files.walk(rootDir)
                .filter(matcher::matches)
                .forEach(Start::modify);
    }

    private static void modify(Path p) {
        System.out.println(p.toString());
    }

This part .forEach(Start::modify); executes the static method modify from the same class where the lambda expression is located. Is there a possibility to add something like else clause when no PDF file is found?

Solution:

You could collect the result after the filter operation into a list instance and then check the size before operating on it.

List<Path> resultSet = Files.walk(rootDir)
                            .filter(matcher::matches)
                            .collect(Collectors.toList());
if(resultSet.size() > 0){
    resultSet.forEach(Start::modify);
}else {
    // do something else   
}

Alternatively, you could do something like this:

if(Files.walk(rootDir).anyMatch(matcher::matches)) {
         Files.walk(rootDir)
              .filter(matcher::matches)
              .forEach(Start::modify);
}else {
        // do something else    
}

Java8 group a list of lists to map

I have a Model and a Property class with the following signatures:

public class Property {

    public String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class Model {

    private List<Property> properties = new ArrayList<>();

    public List<Property> getProperties() {
        return properties;
    }
}

I want a Map<String, Set<Model>> from a List<Model> where the key would be the name from the Property class. How can I can I use java8 streams to group that list by its Properyes’ name? All Propertyes are unique by name.

It is possible to solve in a single stream or should I split it somehow or go for the classical solution?

Solution:

yourModels.stream()
          .flatMap(model -> model.getProperties().stream()
                  .map(property -> new AbstractMap.SimpleEntry<>(model, property.getName())))
          .collect(Collectors.groupingBy(
                Entry::getValue, 
                Collectors.mapping(
                    Entry::getKey, 
                    Collectors.toSet())));

Java: Naming convention for plural acronyms

I know there had already been similar discussions on such naming conventions. However, I’m having problem with plural acronyms.

public List<Disc> findAllDvds(DiscHolder holder) {}
public List<Disc> findAllDvd(DiscHolder holder) {}

Assuming that I have decided to use CamelCase for acronyms, which of the two is generally more acceptable?

Edit

I am aware this will invite opinion-based answers, but sometimes when you are in doubt, you just need people to give advises and feedbacks.

To add on, the confusing part here is that findAllDvds can imply a new acronym DVDS, and it can be considered confusing.

Solution:

The first (findAllDvds). The second (findAllDvd) is simply incorrect, “all” implies more than one, but “Dvd” is singular in English.

Re your edit:

the confusing part here is that findAllDvds can imply a new acronym DVDS, and it can be considered confusing

Since the “all” implies multiple, the “s” on “Dvds” reads as a plural, not part of the acronym. If it really were DVDS, the name would be findAllDvdss or similar.

It’s said that in computer science, there are three hard problems: Cache invalidation, and naming things. (Off-by-one errors are just common, not hard.)

How to extract used byte array from ByteBuffer?

The java.nio.ByteBuffer class has a ByteBuffer.array() method, however this returns an array that is the size of the buffer’s capacity, and not the used capacity. Due to this, I’m having some issues.

I have a ByteBuffer which I am allocating as some size and then I am inserting data to it.

ByteBuffer oldBuffer = ByteBuffer.allocate(SIZE);
addHeader(oldBuffer, pendingItems);
newBuffer.flip();
oldBuffer.put(newBuffer);
// as of now I am sending everything from oldBuffer
send(address, oldBuffer.array());

How can I just send what is being used in oldBuffer. Is there any one liner to do this?

Solution:

You can flip the buffer, then create a new array with the remaining size of the buffer and fill it.

oldBuffer.flip();
byte[] remaining = new byte[oldBuffer.remaining()];
oldBuffer.get(remaining);

Another way in a one liner with flip() and Arrays.copyOf

oldBuffer.flip();
Arrays.copyOf(oldBuffer.array(), oldBuffer.remaining());

And without flip()

Arrays.copyOf(oldBuffer.array(), oldBuffer.position());

Also like EJP said, if you have access to the send(..) method, you can add a size and offset argument to the send() method, and avoid the need to create and fill a new array.

Java ArrayList.removeAll(), but for indices

Is there a way to do something like this:

ArrayList<String>.removeAll(ArrayList<Integer>)

With the ArrayList<Integer> being the indices that I want deleted. I know that I could iterate through the indices list and use remove(index), but I was wondering if there is a one-command way of doing so.

I know how to put this iteration into one line, my question is, if there is a way implemented by oracle.

Solution:

You can use a Stream to iterate through the indices to remove. However, take care to remove the highest index first, to avoid shifting other elements to remove out of position.

public void removeIndices(List<String> strings, List<Integer> indices)
{
     indices.stream()
         .sorted(Comparator.reverseOrder())
         .forEach(strings::remove);
}

For removing from a list of Strings this will work, calling the proper remove(int) method. If you were to try this on a List<Integer>, then you will have to avoid calling remove(E) by calling .mapToInt(Integer::intValue) before calling forEach.

Is it a good practice to nullifying String in java

I have a problem with storing a plain password in memory as a String. According to the reference, since Strings are immutable there is a vulnerability of using String data type for sensitive data storing in memory.

https://www.geeksforgeeks.org/use-char-array-string-storing-passwords-java/

Why is char[] preferred over String for passwords?

Can I overcome this security issue by nullifying the string variable instead of using char array or String buffer/builder.

eg : String password=”password”;
password = null;

Solution:

No. Nullifying a string would only delink the reference. But the value will still exist in string pool. Because to conserve memory, string values are retained in the string pool.

Any potential hacker, can retrieve the value by gaining access to the string pool.

Whereas, using char[], you can simply treat that object as any other object. And nullifying the char object will wipe off the data from heap at the time of garbage collection.

An even better option will be using a byte array.

Read more about String Constant pool.

Java ArrayList, how to ignore a value from the object when using contains()

I have a class like that:

public class Student implements Serializable{
  private String name;
  private int age;
  private Image img;
}

I store a few students in an ArrayList and write them to a file. When I restart the application I load them from that file again. However, the Image img variable is constantly changing. That means when I use arrayList.contains(studentA) it’s not the same object anymore, so arrayList.remove(studentA) won’t work.

Is there an easy way to either: Only check for the name of the student or ignore the Image field when using contains()?

Solution:

Yes.

Just implement the equals/hashcode without the Image attribute.

public class Student implements Serializable {

    private String name;
    private int age;
    private Image img;

    @Override
    public boolean equals(final Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age &&
                Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {

        return Objects.hash(name, age);
    }

}

Java: Sum two or more time series

I have multiple time series:

       x
|    date    | value |
| 2017-01-01 |   1   |
| 2017-01-05 |   4   |
|     ...    |  ...  |

       y
|    date    | value |
| 2017-01-03 |   3   |
| 2017-01-04 |   2   |
|     ...    |  ...  |

Frustratingly in my dataset there isn’t always a matching date in both series. For scenarios where there is one missing I want to use the last available date (or 0 if there isnt one).
e.g for 2017-01-03 I would use y=3 and x=1 (from the date before) to get output = 3 + 1 = 4

I have each timeseries in the form:

class Timeseries {
    List<Event> x = ...;
}

class Event {
    LocalDate date;
    Double value;
}

and have read them into a List<Timeseries> allSeries

I thought I might be able to sum them using streams

List<TimeSeries> allSeries = ...
Map<LocalDate, Double> byDate = allSeries.stream()
    .flatMap(s -> s.getEvents().stream())
.collect(Collectors.groupingBy(Event::getDate,Collectors.summingDouble(Event::getValue)));

But this wouldnt have my missing date logic I mentioned above.

How else could I achieve this? (It doesnt have to be by streams)

Solution:

I’d say you need to expand the Timeseries class for the appropriate query function.

class Timeseries {
    private SortedMap<LocalDate, Integer> eventValues = new TreeMap<>();
    private List<Event> eventList;

    public Timeseries(List<Event> events) {
        events.forEach(e -> eventValue.put(e.getDate(), e.getValue());
        eventList=new ArrayList(events);
    }
    public List<Event> getEvents() {
        return Collections.unmodifiableList(eventList);
    }

    public Integer getValueByDate(LocalDate date) {
        Integer value = eventValues.get(date);
        if (value == null) {
            // get values before the requested date
            SortedMap<LocalDate, Integer> head = eventValues.headMap(date);
            value = head.isEmpty()
                ? 0   // none before
                : head.get(head.lastKey());  // first before
        }
        return value;
    }
}

Then to merge

Map<LocalDate, Integer> values = new TreeMap<>();
List<LocalDate> allDates = allSeries.stream().flatMap(s -> s.getEvents().getDate())
    .distinct().collect(toList());

for (LocalDate date : allDates) {
    for (Timeseries series : allSeries) {
        values.merge(date, series.getValueByDate(date), Integer::ad);
    }
}

Edit: actually, the NavigableMap interface is even more useful in this case, it makes the missing data case

Integer value = eventValues.get(date);
if (value == null) {
    Entry<LocalDate, Integer> ceiling = eventValues.ceilingKey(date);
    value = ceiling != null ? eventValues.get(ceiling) : 0;
}

"array initializer needs an explicit target-type" – why?

Following JEP 286: Local-Variable Type Inference description

I am wondering, what the reason of introducing such a restriction, as:

Main.java:199: error: cannot infer type for local variable k

    var k = { 1 , 2 };
        ^   
(array initializer needs an explicit target-type)

So for me logically it should be:

var k = {1, 2}; // Infers int[]
var l = {1, 2L, 3}; // Infers long[]

Because Java compiler can already infer properly the type of an array:

void decide() {
    arr(1, 2, 3);  // call  void arr(int ...arr)
    arr(1, 2L, 3); // call  void arr(long ...arr)
}

void arr(int ...arr) {
}

void arr(long ...arr) {
}

So what is the impediment?

Solution:

Every time we improve the reach of type inference in Java, we get a spate of “but you could also infer this too, why don’t you?” (Or sometimes, less politely.)

Some general observations on designing type inference schemes:

  • Inference schemes will always have limits; there are always cases at the margin where we cannot infer an answer, or end up inferring something surprising. The harder we try to infer everything, the more likely we will infer surprising things. This is not always the best tradeoff.
  • It’s easy to cherry-pick examples of “but surely you can infer in this case.” But if such cases are very similar to other cases that do not have an obvious answer, we’ve just moved the problem around — “why does it work for X but not Y where X and Y are both Z?”
  • An inference scheme can always be made to handle incremental cases, but there is almost always collateral damage, either in the form of getting a worse result in other cases, increased instability (where seemingly unrelated changes can change the inferred type), or more complexity. You don’t want to optimize just for number of cases you can infer; you want to optimize also for an educated user’s ability to predict what will work and what will not. Drawing simpler lines (e.g., don’t bother to try to infer the type of array initializers) often is a win here.
  • Given that there are always limits, its often better to choose a smaller but better-defined target, because that simplifies the use model. (See related questions on “why can’t I use type inference for the return type of private methods. The answer is we could have done this, but the result would be a more complicated user model for small expressive benefit. We call this “poor return-on-complexity.”)