-2

Is there a way in Java to access two or more non-consecutive indexes of an array at the same time?

For example, I have the following array:

int myArray = {1, 3, 5, 7, 9}

I know I can access one single index or consecutive indexes (using Arrays.copyOfRange) of this array. But if want to print out indexes 1 and 3 of this array; do I have to use the following:

System.out.print(myArray[1] + myArray[3])

I am expecting some syntax like the following; clearly, they are wrong

System.out.print(myArray[1,3])

or

int indexes = {1,3}

System.out.print(myArray[indexes])

Kevin.J
  • 3
  • 1
  • 3
    `System.out.print(myArray[1] + myArray[3])` - Is this attempt failing in some way? It's not clear to me what the problem is. – David Oct 06 '22 at 14:26
  • 5
    Nope, no such syntax in Java. – Thilo Oct 06 '22 at 14:26
  • Why would you expect a variable declared to hold a single `int` to be able to hold multiple `int`s? – Scott Hunter Oct 06 '22 at 14:27
  • 1
    What you seem to be referring to is known as a `slice` in some languages; Java is not one of them. – Scott Hunter Oct 06 '22 at 14:28
  • Btw, `Arrays.copyOfRange` doesn't let you access "consecutive indexes", it creates a *copy* of the provided array in a range (hence the name of the method). So you're creating a subarray that you'll have to access element-wise just like in your working example. – QBrute Oct 06 '22 at 14:29
  • Thank you all for your comments! I think Scott pointed out exactly what I was trying to say as I am new to Java. – Kevin.J Oct 06 '22 at 14:36

1 Answers1

0

It is not possible to access different indices "at once", but you can easily print multiple values:

System.out.printf("%d, %d", myArray[1], myArray[3])
knittl
  • 246,190
  • 53
  • 318
  • 364