Array of classes which create instances - java

having Obj class which in his constructor has System.out.println("Hello world!") ;
I create an array of this class using - Obj[] objArray = new Obj[10] ; and nothing printed , means - no instance of Obj has been called . Is there any way to create such array ,but with instances , beyond create them in for loop ?

Well, since you want to know a way apart from using a for loop, you can do this: -
Obj[] objArray = {new Obj(), new Obj(), new Obj()};
What happens here is, you are initializing your array reference directly with array elements.
Now the type of actual array object is inferred from type of array reference on the LHS.
So, with that declaration, an array of size 3 (in the above case) is created, with each index in the array initialized with the instance of Obj class in the given order.
A better way that I would suggest is to use an ArrayList, in which case, you have double-braces initialization to initialize your List without for loop. And plus with an added advantage that you can anytime add new elements to it. As it dynamically increasing array.
List<Object> list = new ArrayList<Object>() {
{
add(new Obj());
add(new Obj());
add(new Obj());
}
}; // Note the semi-colon here.
list.add(new Obj()); // Add another element here.

Answers so far are good and helpful. I'm here just to remind you about
Obj[] objArray = new Obj[10];
Arrays.fill(objArray, new Obj());
Though, this will only assign one reference (to a new Obj()) to all of the elements of array.

When you do Obj[] objArray = new Obj[10] ;
You only create an array of references to point to the actual 'Obj` object.
But in your case the actual Obj object is never created.
for (int i = 0; i < objArray.length; i++) {
objArray[i] = new Obj();
}
Doing above will print the desired.
Finally do System.out.println(Arrays.deepToString(objArray)) to print toString() of all the Obj

Obj[] objArray = new Obj[10] ; just creates an array capable of holding 10 Objs. To place Objs into the array you need to either use Rohit's approach or write a simple for loop to initialize the array entries one at a time:
for (int i = 0; i < 10; i++) {
objArray[i] = new Obj();
}
Or, without a for loop:
int i = 0;
while (i < 10) {
objArray[i] = new Obj();
i++;
}

Related

Constructors when creating a array of Objects [duplicate]

This question already has answers here:
How to initialize an array in Java?
(11 answers)
Closed 6 years ago.
When I'm creating an array of objects, how can I add the argument for the constructor inside each object? Like this:
foos = new Foo[10];
How do I make 10 objects with their constructors? I do not understand where do I put the arguments that is passed to the constructors of every object?
foos = new Foo[10];
creates an array that can hold references to 10 Foo instances. However, all the references are initialized to null.
You must call the constructor for each element of the array separately, at which point you can specify whatever argument you wish :
foos[0] = new Foo (...whatever arguments the constructor requires...);
...
This is just the allocation for a new array object of type Foo to hold multiple elements. In order to create and store actual object you will do something like this:
foos[0]=new Foo(); //Call constructor here
.
.
.
foos[10]= new Foo(); //Call constructor here
foos = new Foo[10];
This is create an array type Foo, this is not creating object
for Initializing do following:
for(int i=0;i<foos.length; i++){
foos[i] = new Foo (your-argument);
}
See Arrays for more details
You can do it inline like so:
Foo[] foos = new Foo[] {
new Foo(1),
new Foo(2),
new Foo(10)
};
Or like so:
Foo[] foos = {
new Foo(1),
new Foo(2),
new Foo(10)
};
let's say that Foo take a String as an argument so the constructor for Foo is something like this:
public Foo(String arg){
this.arg = arg;
}
if arguments you need to pass to the constructors are different from each other, so you will need to use separate initialization for every element. as #Sanjeev mentioned but with passing an argument.
foos[0]=new Foo(argOne);
.
.
foos[10]= new Foo(argTen);
on the other hand if your arguments are related to to an array index, you should use loop as #Sumit mentioned
for(int i=0;i<foos.length; i++){
foos[i] = new Foo (arg + i);
}
So in order to create "10" new objects you need to create the array to hold the objects and then loop over the list while adding a new object to each index of the array.
int foosSize = 10;
Foo[] foos = new foos[foosSize];
for(int i = 0; i < foosSize; i++) {
foos[i] = new Foo();
}
this will create a new foo object and add it to the index in the array you have created.

Initializing an object in an array with a default value - java

Is there a way to define a default value for an object in array to be initialized with?
In the same way that primitive types are initialized when declaring an array of them:
int[] myIntArray = new int[5]; // we now have an array of 5 zeroes
char[] myCharArray = new char[2]; // an array in which all members are "\u0000"
etc.
I'd like to declare an array of objects of a type that I've defined, and have them automatically initialize in a similar fashion.
I suppose this would mean I'd like to run new myObject() for each index in the array (with the default constructor).
I haven't been able to find anything relevant online, the closest I got was to use Arrays.fill(myArray, new MyObject()) after initializing the array (which actually just creates one object and fills the array with pointers to it), or just using a loop to go over the array and initialize each cell.
thank you!
EDIT: I realized this is relevant not just to arrays, but for declaring objects in general and having them default to a value / initialize automatically.
The Java 8 way:
MyObject[] arr = Stream.generate(() -> new MyObject())
.limit(5)
.toArray(MyObject[]::new);
This will create an infinite Stream of objects produced by the supplier () -> new MyObject(), limit the stream to the total desired length, and collect it into an array.
If you wanted to set some properties on the object or something, you could have a more involved supplier:
() -> {
MyObject result = new MyObject();
result.setName("foo");
return result;
}
Do this so you can initialize the array when declaring it:
int[] myIntArray = {0, 0, 0,0,0};
char[] myCharArray = { 'x', 'p' };
you could of course do:
int[] myIntArray = new int[5];
and the in a for loop set all indexes to the initial value... but this can take a while if the array is bigger...
Edit:
for custom objects is the same just use an anonymous constructor in the init
Example:
public class SOFPointClass {
private int x;
private int y;
public SOFPointClass(int x, int y) {
this.x = x;
this.y = y;
}
// test
public static void main(String[] args) {
SOFPointClass[] pointsArray = { new SOFPointClass(0,0) , new SOFPointClass(1,1)};
}
}
I don't see a way that Java provides to do this.
My suggestion would be define a function to do it.
Object[] initialize(Class aClass, int number) throws IllegalAccessException, InstantiationException {
Object[] result = new Object[number];
for (int i = 0; i < number; ++i) {
result[i] = aClass.newInstance();
}
}
Then call it as Object[] arr = initialize(YourClass.class, 10)
In Java, the array is initialized with the default value of the type. For example, int default is 0. The default value for cells of an array of objects is null as the array cells only hold references to the memory slot contains the object itself. The default reference points to null. In order to fill it with another default value, you have to call Arrays.fill() as you mentioned.
Object[] arr=new Object[2];
Arrays.fill(arr, new Object());
As far as I know there is no way of doing what you want with just plain java (that is to say there may be an external library I don't know about).
I would take the hit and loop over the array. Something like this should work:
myObject[] array = new myObject[5];
for (int i = 0; i < array.length; i++) {
array[i] = new myObject();
}
You could also shorten this using lambdas, like Cardano mentioned in his answer.

for-each loop in java can't be used for assignments

Why for-each loop in java can't be used for assignments?
For eg I am trying the below example and not getting the expected result but compiles successfully:
int count = 0;
String[] obj = new String[3];
for (String ob : obj )
ob = new String("obj" + count++);
System.out.println(obj[0]); // null
ob is a local variable which is a copy of the reference in the array. You can alter it but it doesn't alter the array or collection it comes from.
Essentially, that is correct. The for-each loop is not usable for loops where you need to replace elements in a list or array as you traverse it
String[] obj = { "obj1", "obj2", "obj3" };
or
for (int count = 0; count < obj.length; count++) {
obj[count] = "obj" + count;
}
As you've noted, you can't use the variable in an array iteration to set the values of the array. In fact your code, while legal, is unusual in iterating through the elements of an array in order to initialise them. As other answers have noted, you are better off using the index of the array.
Even better is to create the array in the process of initialisation. For example, in Java 8 you could use:
String[] obj = IntStream.range(0, 4).mapToObj(n -> "obj" + n).toArray();
This seems to me to capture your intent of creating strings and then turning them into a new array rather than create an array and then iterate through it changing each element.

array of objects proper way of use?

What I have is
public static LinkedList<Mp3> musicList;
...
if (musicList == null) {
musicList = new LinkedList<Mp3>();
}//create... this works
but if I have like 5 or more lists how can I do something like this:
Object[] ob = new Object[]{musicList,musicList2,...,musicList10};
for (int i = 0; i < ob.length; i++){
if (ob[i] == null) ob[i] = new LinkedList<Mp3>();
}
If I put it in first way it's working; how can I put it in like in second snippet?
Avoid mixing arrays and generics.
Instead, consider this:
List<List<Mp3>> listsList = new ArrayList<List<Mp3>>();
listsList.add(new LinkedList<Mp3>());
Changing the references in the array will not change the original references used to create the array.
The references in the array are a copy of what was in the initialization.
What you should do is get rid of the musicListN variables and only have an array, or better yet use a List.
List<List<Mp3>> musicLists = new ArrayList<List<Mp3>>(LIST_COUNT);
for (int i = 0; i < LIST_COUNT; i++) {
musicLists.add(new LinkedList<Mp3>());
}
Then use musicLists.get() to everywhere you would have used the older variables.
If you really want to do one line object list initialization, look at this Q. Initialization of an ArrayList in one line

How can I create an Array of ArrayLists?

I am wanting to create an array of arraylist like below:
ArrayList<Individual>[] group = new ArrayList<Individual>()[4];
But it's not compiling. How can I do this?
As per Oracle Documentation:
"You cannot create arrays of parameterized types"
Instead, you could do:
ArrayList<ArrayList<Individual>> group = new ArrayList<ArrayList<Individual>>(4);
As suggested by Tom Hawting - tackline, it is even better to do:
List<List<Individual>> group = new ArrayList<List<Individual>>(4);
As the others have mentioned it's probably better to use another List to store the ArrayList in but if you have to use an array:
ArrayList<Individual>[] group = (ArrayList<Individual>[]) new ArrayList[4];
You will need to suppress the warning but it's safe in this case.
This works:
ArrayList<String>[] group = new ArrayList[4];
Though it will produce a warning that you may want to suppress.
You can create a class extending ArrayList
class IndividualList extends ArrayList<Individual> {
}
and then create the array
IndividualList[] group = new IndividualList[10];
You can create Array of ArrayList
List<Integer>[] outer = new List[number];
for (int i = 0; i < number; i++) {
outer[i] = new ArrayList<>();
}
This will be helpful in scenarios like this. You know the size of the outer one. But the size of inner ones varies. Here you can create an array of fixed length which contains size-varying Array lists. Hope this will be helpful for you.
In Java 8 and above you can do it in a much better way.
List<Integer>[] outer = new List[number];
Arrays.setAll(outer, element -> new ArrayList<>());
This works, array of ArrayList. Give it a try to understand how it works.
import java.util.*;
public class ArrayOfArrayList {
public static void main(String[] args) {
// Put the length of the array you need
ArrayList<String>[] group = new ArrayList[15];
for (int x = 0; x < group.length; x++) {
group[x] = new ArrayList<>();
}
//Add some thing to first array
group[0].add("Some");
group[0].add("Code");
//Add some thing to Secondarray
group[1].add("In here");
//Try to output 'em
System.out.println(group[0]);
System.out.println(group[1]);
}
}
Credits to Kelvincer for some of codes.
The problem with this situation is by using a arraylist you get a time complexity of o(n) for adding at a specific position. If you use an array you create a memory location by declaring your array therefore it is constant
You can't create array of generic type. Create List of ArrayLists :
List<ArrayList<Individual>> group = new ArrayList<ArrayList<Individual>>();
or if you REALLY need array (WARNING: bad design!):
ArrayList[] group = new ArrayList[4];
Creation and initialization
Object[] yourArray = new Object[ARRAY_LENGTH];
Write access
yourArray[i]= someArrayList;
to access elements of internal ArrayList:
((ArrayList<YourType>) yourArray[i]).add(elementOfYourType); //or other method
Read access
to read array element i as an ArrayList use type casting:
someElement= (ArrayList<YourType>) yourArray[i];
for array element i: to read ArrayList element at index j
arrayListElement= ((ArrayList<YourType>) yourArray[i]).get(j);
List[] listArr = new ArrayList[4];
Above line gives warning , but it works (i.e it creates Array of ArrayList)
To declare an array of ArrayLists statically for, say, sprite positions as Points:
ArrayList<Point>[] positionList = new ArrayList[2];
public Main(---) {
positionList[0] = new ArrayList<Point>(); // Important, or you will get a NullPointerException at runtime
positionList[1] = new ArrayList<Point>();
}
dynamically:
ArrayList<Point>[] positionList;
int numberOfLists;
public Main(---) {
numberOfLists = 2;
positionList = new ArrayList[numberOfLists];
for(int i = 0; i < numberOfLists; i++) {
positionList[i] = new ArrayList<Point>();
}
}
Despite the cautions and some complex suggestions here, I have found an array of ArrayLists to be an elegant solution to represent related ArrayLists of the same type.
ArrayList<String>[] lists = (ArrayList<String>[])new ArrayList[10];
You can create like this
ArrayList<Individual>[] group = (ArrayList<Individual>[])new ArrayList[4];
You have to create array of non generic type and then cast it into generic one.
ArrayList<Integer>[] graph = new ArrayList[numCourses]
It works.
I think I'm quite late but I ran into the same problem and had to create an array of arraylists as requested by my project in order to store objects of different subclasses in the same place and here is what I ended up doing:
ArrayList<?>[] items = new ArrayList[4];
ArrayList<Chocolate> choc = new ArrayList<>();
ArrayList<Chips> chips = new ArrayList<>();
ArrayList<Water> water = new ArrayList<>();
ArrayList<SoftDrink> sd = new ArrayList<>();
since each arraylist in the array would contain different objects (Chocolate , Chips , Water and SoftDrink )
--it is a project to simulate a vending machine--.
I then assigned each of the Arraylists to an index of the array:
items[0]=choc;
items[1]=chips;
items[2]=water;
items[3]=sd;
Hope that helps if anyone runs into a similar issue.
I find this easier to use...
static ArrayList<Individual> group[];
......
void initializeGroup(int size)
{
group=new ArrayList[size];
for(int i=0;i<size;i++)
{
group[i]=new ArrayList<Individual>();
}
You can do thi. Create an Array of type ArrayList
ArrayList<Integer>[] a = new ArrayList[n];
For each element in array make an ArrayList
for(int i = 0; i < n; i++){
a[i] = new ArrayList<Integer>();
}
If you want to avoid Java warnings, and still have an array of ArrayList, you can abstract the ArrayList into a class, like this:
public class Individuals {
private ArrayList<Individual> individuals;
public Individuals() {
this.individuals = new ArrayList<>();
}
public ArrayList<Individual> getIndividuals() {
return individuals;
}
}
Then you can safely have:
Individuals[] group = new Individuals[4];
ArrayList<String> al[] = new ArrayList[n+1];
for(int i = 0;i<n;i++){
al[i] = new ArrayList<String>();
}
you can create a List[] and initialize them by for loop. it compiles without errors:
List<e>[] l;
for(int i = 0; i < l.length; i++){
l[i] = new ArrayList<e>();
}
it works with arrayList[] l as well.

Categories

Resources