0

I am in a beginner's Java class. I only know basic Java. We just started polymorphism and Inheritance. My problem is placing objects into an array. I have an array of ten Runner objects as follows.

import java.util.*;

public class Race 
{

    public static void main(String []args)
    {

        Runner r1 = new Runner("Jack Sprat", 10);
        Runner r2 = new Runner("Cecil Litwack", 8);
        Runner r3 = new Runner("Dina Might", 3);
        Runner r4 = new Runner("Seymour Butts", 4);
        Runner r5 = new Runner("Ima reject", 1 );
        Runner r6 = new Runner("Ivan Earache", 9);
        Runner r7 = new Runner("Ace Ventura", 6);
        Runner r8 = new Runner("Joan O'Farc", 7);
        Runner r9 = new Runner("Jack O'Lantern", 5);
        Runner r10 = new Runner("Jim Nasium", 2);

        Runner[] raceArray = new Runner[10];

        raceArray[0] = r1;
        raceArray[1] = r2;
        raceArray[2] = r3;
        raceArray[3] = r4;
        raceArray[4] = r5;
        raceArray[5] = r6;
        raceArray[6] = r7;
        raceArray[7] = r8;
        raceArray[8] = r9;
        raceArray[9] = r10;

Let's say I want to place the object at index 1 into index 0, will the object at index 0 go to index 1? Or will the object at index 0 be removed from the array? If it is removed how do I make it to when I place an object at a different array index the objects just trade places in the array?

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Todd
  • 129
  • 1
  • 1
  • 9
  • With `Lists`, you can remove items from the list and insert them at arbitrary positions in the list. Arrays are very poorly suited to this task. – David Conrad Jan 04 '16 at 22:48

2 Answers2

3

First of all you do not store objects into arrays, you store references to objects in an array.

In case you later set raceArray[0] = raceArray[1]; from now on the zero-th and first item in raceArray will both refer to r2. It means that r1 is no longer references from that array. That does not necessary means r1 is gone since other things can stil refer to it.

In order to swap places, you can use the following code:

Runner temp = raceArray[0];
raceArray[0] = raceArray[1];
raceArray[1] = temp;

What you do is you create a temp - a temporary variable - that refers to the same object as does the array at index 0, next you overwrite index 0 with the reference at index 1, finally you overwrite index 1 with the value in temp.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
3

Arrays contains references to objects. So when you'll execute raceArray[0] = raceArray[1] both memory segments will contain a reference to the same r2 object.

Aaron
  • 24,009
  • 2
  • 33
  • 57