0

I'm trying to build a BlueJ project that have parameterized constructor where one of the parameter is of type ArrayList<String>

public class Bike
{
    // instance variables 
    private String bikeNumber;
    private ArrayList<String> bikeColour;

    /**
     * Constructor for objects of class Bike
     * default constructor
     */
    public Bike()
    {
        bikeNumber = " ";
        bikeColour = new ArrayList<String>();
    }

    /**
     * Parameterised constructor 
     */
    public Bike(String number, ArrayList<String> colour)
    {
        bikeNumber = number;
        bikeColour = colour;
    }    

}

How can I pass the value for colour while calling the constructor in BlueJ ?

enter image description here

Tom
  • 16,842
  • 17
  • 45
  • 54
Mahen J
  • 9
  • 1
  • 2
    `new Bike("number", new ArrayList<>())`. In general, you don't really require an `ArrayList`, but can probably take a more general `List` (you should be taking a defensive copy in the constructor anyway). – Andy Turner May 17 '21 at 09:16

2 Answers2

0

After a quick glance at a BlueJ tutorial I think this not the intended way. Instead consider initializing the list field:

private List<String> bikeColours = new ArrayList<>();

And adding methods for addition and retrieval:

public void addColour(String colour) {
    bikeColours.add(colour);
}

public List<String> getColours() {
    return new ArrayList<>(bikeColours);
}

Another way to expose a collection I sometimes use is with a Stream, which is read-only by nature:

public Stream<String> getColours() {
    return bikeColours.stream();
}

This might not be useful in the context of BlueJ.

Note that fields/variables are usually declared as List, whilst they may be initialized as ArrayList. The List interface hides the fact that an ArrayList implementation is used, and allows switching to a different implementation later on.

If you do need a constructor with a collection parameter it's a good idea to make a copy of it, to avoid manipulations on the provided collection making unexpected changes to the internal data of this instance:

public Bike(String number, List<String> colours) {
    this.number = number;
    this.colours = new ArrayList(colours);
}

Regarding the naming. I would not name the fields 'bikeNumber' and 'bikeColour' since they are already members of the 'Bike' class. 'number' and 'colour' should suffice. Name clashes between parameters and fields can be averted by referencing the fields using 'this.' as shown above. Since multiple colours are stored, I would name the field in the plural 'colours' rather than the singular 'colour'.

Adriaan Koster
  • 15,870
  • 5
  • 45
  • 60
0

That's easy

When you create an object you just pass it to the constructor.

Eg:

Bike obj = new Bike("1234XY",colors)

Dharman
  • 30,962
  • 25
  • 85
  • 135