I have a class called Car, 6 other classes (Van,Cab,Truck, Taxi, Sedan and Motorbike) that implement this class. Each of the subclasses has its own mnethods and attributes.

How would I go about creating an array of these vehicles with the type of car being randomly selected. that is I would like to have an array that looks like this

ArrayLaneSouth = {Van,Cab, Taxi, Sedan}
ArrayLaneNorth = {Van,Cab, Taxi, Sedan}
ArrayLaneWest = {Van,Cab, Taxi, Sedan}
ArrayLaneEast = {Van,Cab, Taxi, Sedan}

the elements in the arrays are types of cars and the type be selected randomly.

classes can't 'implement' classes, only extend them. Unless of course Car is an interface, not a class.
basically, this can be done with (a bit) the same logic as ye olde "roll the dice".

in here, the possible values are not "1-2-3-4-5-6", but, let's say you have an array of existingTypes:

String[] existingTypes = {"Van", "Cab", "Taxi", "Sedan"};

Here, your possible values are: "0-1-2-3", the valid indices of your array.

Based on the information you can find here: http://stackoverflow.com/questions/12860398/basic-random-rolling-dice-java

you can easily write a method getRandomIndex() that returns a random index for you to use.

then you can implement something like:

Car[] newArray = new Car[x]; // x being the number of elements you want.
for ( int i = 0; i < x; i++){
switch(getRandomIndex()){
  case 0: newArray[i] = new Van();
    break;
  case 1: newArray[i] = new Cab();
      break;
  case 2: newArray[i] = new Taxi();
      break;
    case 3:
    default: newArray[i] = new Sedan();
    break;
}

No need for the Strings or the switch, classes are Classes in their own right!

Class[] carTypes = {Van.class, Cab.class ... };
for ( int i = 0; i < x; i++) {
   newArray[i] = (Car) carTypes[getRandomIndex()].newInstance();
}

Thanks it worked nicely

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.