Aleksei Moshkov Aleksei Moshkov - 3 years ago 181
Java Question

Find element and print a part of massive

I need to print into console part of elements. There is a massive [1,2,4,4,2,3,4,1,7]. I have to find last element, which contains "4", and print the rest of massive after this element. At this manner I have to get [1,7]. Maybe there is exist more simple way, please give me advice.

import java.util.ArrayList;

public class Main {

public static void main(String[] args) {
ArrayList <Integer> array = new ArrayList<Integer>();

int i = (Integer) array.lastIndexOf(4); //Java don't uderstand this

for (i = array.lastIndexOf(4); i < array.size()+1; i++) {
System.out.println(array.indexOf(i)); //try to print element 6,7 and 8 of Array

Answer Source

According to Java docs for ArrayList:

public int lastIndexOf(Object o)

Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element

int idx = list.lastIndexOf(new Integer(4)); //get last index of element with 4
if(list.size() > (idx+1))                   //check if idx is index of the last element
    for(int i=idx+1; i<list.size(); i++)
        System.out.println(list.get(i));   //print everything after the last element with 4

If you are printing inclusive of the element with 4, then you don't need the if and you print from int i = idx.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download