Index of last not null object from Array. - Java Collection Framework

Java examples for Collection Framework:Array Index

Description

Index of last not null object from Array.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        Object[] objects = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        System.out.println(lastNonNullValueIndex(objects));
    }/*  www.j  a  v a2s .  c o m*/

    /**
     * Index of last last not null object.
     * 
     * If objects is null or all objects values are null returns -1;
     * 
     * @param objects
     * @return
     */
    public static int lastNonNullValueIndex(final Object[] objects) {

        int i = -1;
        if (objects != null) {
            for (i = objects.length - 1; i >= 0; i--) {
                if (objects[i] != null) {
                    break;
                }
            }
        }
        return i;
    }
}

Related Tutorials