Yes, it is possible to add multiple int
to an array, but you would need to have an array where each item is an Object
rather than an int
.
For example...
// the items to store in the array, which contain 3 ints
public class Bucket {
int number1 = -1;
int number2 = -1;
int number3 = -1;
public void addInt(int number){
if (number1 == -1){
number1 = number;
}
else if (number2 == -1){
number2 = number;
}
else if (number3 == -1){
number3 = number;
}
}
}
// the array, as used in other classes
Bucket[] bArray = new Bucket[6]; // 6 items in the array, where each item is a Bucket that contains 3 ints
// assigning ints into the array
bArray[2].addInt(56); // add the int '56' to the bucket at index '2' of the array
// You could also use other Array-like structures
ArrayList<Bucket> bList = new ArrayList<Bucket>();
Of course, if you don't always have <=3 items in a bucket, you could just change the Bucket class to use an array or a List
as its variable rather than separate int
s.
You could also use multi-dimensional arrays...
// creating the buckets
int[][] buckets = new int[6][3];
// assigning ints into the array
bArray[2][0] = 56; // add the int '56' to the bucket at index '2' of the array, position '0'
It would get a little messy, however, if you start playing around with different-sized buckets, and you'd need to do more error-checking to ensure that...
- The items in the bucket aren't empty when you try to access them
- When you're adding a number to a bucket, you need to detect the next position in the second dimension that is empty, so you don't overwrite the
int
s that are already in there.
If is for these reasons why I would recommend using an Object-based array over a multi-dimensional array.