0

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>();
            array.add(0,1);
            array.add(1,2);
            array.add(2,4);
            array.add(3,4);
            array.add(4,2);
            array.add(5,3);
            array.add(6,4);
            array.add(7,1);
            array.add(8,7);

             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
            }
        }
    }
  • 1
    Hint: read carefully what the [Java doc for `indexOf()` says](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#indexOf-java.lang.Object-) and compare it with [`get()`](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#get-int-). – markspace Jul 23 '17 at 01:19
  • suppose you refer this [post](https://stackoverflow.com/questions/4962361/where-is-javas-array-indexof) it may be helpful. – Rajith Pemabandu Jul 23 '17 at 01:51
  • I look at the specific of "get" method in post, but actually it isn't helpfull. I guess, I need write my own method, which based on "IndexOf" or "LastIndexOf" method. In the snippet above I found the part of Massive, which I want to use further, but I don't have correct method to do this, "fori" didn't give me correct list... – Aleksei Moshkov Jul 23 '17 at 09:57
  • *I have to find last element, which contains "4"* how ? – Ravi Oct 02 '17 at 15:24
  • @AlekseiMoshkov You may take a look at my solution, though it been a while since you posted your question. – user3437460 Oct 02 '17 at 15:39

1 Answers1

1

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(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.

Community
  • 1
  • 1
user3437460
  • 17,253
  • 15
  • 58
  • 106