0

here Is Code there any way to get Index of the object from the list by calling a method in the list.

for example something like this:

class A{
    String a="";
    String b="";
}

List<A> alist= new ArrayList();

for (A a : alist) {
    a.getIndexInList();
}
Andronicus
  • 25,419
  • 17
  • 47
  • 88
Ahmad R. Nazemi
  • 775
  • 10
  • 26

2 Answers2

3

Why not use indexOf? If I recall correctly it is a built-in function of list.

 List<A> alist= new ArrayList<>();
 for (A a : alist) {
     int index = alist.indexOf(a);
 }

Only the list can give you the index. Unless the object in the array knows it's in an array it can't give you it's index.

Richard Barker
  • 1,161
  • 2
  • 12
  • 30
  • 1
    It's slower than using your own counter. We know the ordering, `indexOf` will perform lookup every time. – Andronicus Sep 05 '19 at 05:29
  • 1
    Also you did not mention `equals` and `hashCode`. There are reasons, when `hashCode` is left returning constant value - this won't work then. – Andronicus Sep 05 '19 at 05:31
  • 1
    @Richard Baker what if there are duplicate elements? indexOf() returns first occurrence. – raviraja Sep 05 '19 at 07:14
  • All of which are implementation details the OP didn't mention. Yes, it's slower than making your own loop, yes if hashcode and equals are incorrect the results will be as well, and yes duplicates will return the first - all of which is true for just about every other function on a list. – Richard Barker Sep 05 '19 at 12:53
2

There is no builtin solution, you can use external counter:

List<A> alist= new ArrayList();
int counter = 0;
for (A a : alist) {
    // logic
    counter++;
}

You could also create a map with indices as keys, something like:

IntStream.range(0, alist.size()).mapToObj(Integer::valueOf)
    .collect(Collectors.toMap(
            Function.identity(),
            alist::get
    ));

but alist needs to be effectively final.

Andronicus
  • 25,419
  • 17
  • 47
  • 88