2

This is the IntArrayBag I'm talking about. For the sake of the question, here are the data fields and the constructor:

   private int[ ] data;
   private int manyItems;

   public IntArrayBag( )
   {
      final int INITIAL_CAPACITY = 10;
      manyItems = 0;
      data = new int[INITIAL_CAPACITY];
   }

My question is, how could I make this class generic so that this method would take any type of object as an argument (instead of an integer)? I was thinking about making the array generic but according to this answer arrays cannot be generic and this answer stating that you cannot have generic data fields.

How would one make this class generic then? Thank you!

GreenSaber
  • 1,118
  • 2
  • 26
  • 53
  • 2
    The same way `ArrayList` does - look at [the code](http://hg.openjdk.java.net/jdk10/jdk10/jdk/file/777356696811/src/java.base/share/classes/java/util/ArrayList.java). – Boris the Spider Apr 02 '18 at 15:32

1 Answers1

3

You can make the class generic by using List<T>:

public class ArrayBag<T> {
    private List<T> data;
    private int manyItems;
    public IntArrayBag() {
        final int INITIAL_CAPACITY = 10;
        manyItems = 0;
        data = new ArrayList<T>();
   }
}

This would take care of non-primitive types. Primitives would require boxing, making the class sub-optimal for use with ints, longs, etc.

Note that you would need to use equals in place of == in situations like this:

if (target == data[index]) ...

The above should be rewritten as

if (target.equals(data[index])) ...

after checking target for null.

You could also "piggyback" on ArrayList<T>'s ability to grow automatically, which will let you remove array growth logic from your class.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Wow is it really that easy...? I'll go test it out, thanks for the quick answer! :) – GreenSaber Apr 02 '18 at 15:35
  • 2
    This answer is slightly misleading. The OP seems to think you can't have a field of type `T[]` and by suggesting to use `List` instead it could be interpreted as confirming that. – Paul Boddington Apr 02 '18 at 15:36
  • 1
    @PaulBoddington You are right. However, I didn't want to suggest to OP to stay with generic arrays because of the headaches he'd have with them. Using `List` should be the "default" solution, even though the alternative solution is definitely possible. – Sergey Kalinichenko Apr 02 '18 at 15:41