V
V
Vladimir Mikhalik2015-04-23 21:57:51
Java
Vladimir Mikhalik, 2015-04-23 21:57:51

How to find the indexes of duplicate elements in an array?

Hello community. I'm a newbie, so please don't kick too hard.
Let's say we have an integer 5 and a one-dimensional array {1,2,4,5,2,5,7,5,2,8,1}.
The question is, how do I find out the indexes of array elements equal to 5?
upd . Thanks to those who responded, thought and decided.

public static void main(String[] args) {
  
    int a = 5;
    int [] array = new int []{1,2,4,5,2,5,7,5,2,8,1};

    for(int i = 0; i < array.length; i++){
      if(array[i] == a){
        System.out.println(i);
      }
    }
  }

Answer the question

In order to leave comments, you need to log in

4 answer(s)
T
Timur, 2015-04-23
@vladiq88

I won't write the code (you'll have to strain yourself a little), but here's the procedure for you: Cycle through the array starting from the zero element to the last one. Each time get the value from the array at the current loop index. Check this value - is it not a five?. If so then put the current index somewhere. (For a start, you can simply output to the console).
In general, as you wrote above - write at least some code, and we will fix it :)

K
Kirill Olenev, 2015-04-23
@agent10

Write first, what have you already tried to do? Please provide code..

A
Anhedonia, 2015-04-24
@Anhedonia

Something like this

int number = 5;
List<Integer> repeatedIndex = new ArrayList<>();
int[] numbers = {1,2,4,5,2,5,7,5,2,8,1};
for(int i = 0; i < numbers.length(); i++)
{
   if(numbers[i].equals(number);
{
repeatedIndex.add(i);
}

}

P
poisonGreen, 2015-04-24
@poisonGreen

java 8:

public static void main(String[] args) {
        int[] array = { 1, 2, 4, 5, 2, 5, 7, 5, 2, 8, 1 };

        int[] indices = IntStream.range(0, array.length).filter(i -> array[i] == 5).toArray();
        System.out.println(Arrays.toString(indices));
 }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question