Java Creating Objects at Runtime in a For Loop - java

I'm trying to create objects within a for loop at runtime. Here is the (incorrect) code:
for(int i=1;i<max;i++){
Object object(i);
}
I'd like it to create max number of Object objects with names object1, object2, etc. Is there any way to do this? I have been unable to find anything elsewhere online. Thanks for your help!

You want to use a data structure to store a sequence of objects. For example, an array could do this:
Fruit banana[] = new Fruit[10];
for (int i = 0; i < 10; i++){
banana[i] = new Fruit();
}
This creates 10 objects of type Fruit in the banana array, I can access them by calling banana[0] through banana[9]

You could use an array to create multiple objects.
public void method(int max) {
Object[] object = new Object[max];
for (int i = 0; i < max; i++) {
object[i] = new Object();
}
}

Related

Creating class instances stored in a list

So first I make an ArrayList. (? means that I don't know what should be there, keep reading)
ArrayList<?> arrayList = new ArrayList<?>();
So this will store class name of abstract class Class, so for example it might stores ExtendedClass1 or ClassExtended2.
Later I iterate through that ArrayList and create new objects with the name stored in arraylist
for (int i = 0; i < arrayList.size(); i++) {
new arrayList.get(i); // Takes the class name and makes new object out of it
}
How can I actually do it?
You need to store String class names, and then use reflection to create instances, assuming it's reflection that you're going to use:
List<String> arrayList = new ArrayList<>();
arrayList.add("fully.qualified.ExtendedClass1");
arrayList.add("fully.qualified.ClassExtended2");
And then, in your loop:
for(int i = 0; i < arrayList.size(); i++) {
Class<?> cls = Class.forName(arrayList.get(i)); //Get class for the name
Object instance = cls.newInstance();
...
}

Combining a static array with a dynamic ArrayList

I want to combine a static array (such as int[]) with a dynamic array such as ArrayList<String>
For example, I know the count of houses: 10 (fixed), but I don't know the count of humans who live in a house. This count will also change dynamically, like a List.
Is there any option to create a datatype which can fulfill both criteria?
An ArrayList is a dynamicly sized data structure backed by an array. It sounds to me like you could have an array of House where each House has a List<Human> field.
House[] homes = new House[10];
and a class like
class House {
private List<Human> people = new ArrayList<>();
public List<Human> getPeople() {
return people;
}
}
then to get the total count of people in those homes you might use something like
int count = 0;
for (House h : homes) {
count += h.getPeople().size();
}
This works for me:
ArrayList<String>[] house = new ArrayList[15];
for (int x = 0; x < house.length; x++) {
house[x] = new ArrayList<String>();
}
house[0].add("Pete");
house[0].add("Marta");
house[1].add("Dave");
System.out.println(house[0]);
System.out.println(house[1]);
out:
[Pete, Marta]
[Dave]
..i used this Create an Array of Arraylists

HashSet compilation error

The only thing I want to do is putting an array (temp_X) into a HashSet, but I got the error for the HashSet: no suitable constructor found for HashSet(List)
public PSResidualReduction(int Xdisc[][], double[][] pat_cand, int k) {
for (int i = 0; i < Xdisc.length; i++) {
int[] temp_X;
temp_X = new int[Xdisc[0].length];
for (int s = 0; s < Xdisc[0].length; s++) {
temp_X[s] = Xdisc[i][s];
}
HashSet<Integer> temp_XList = new HashSet<Integer>(Arrays.asList(temp_X));
}
}
Any idea how I can fix it?
Arrays#asList accepts a type array which means all elements used need to be Object types rather than primitives.
Use an Integer array instead:
Integer[] temp_X;
This will allow Arrays#asList to be used to against the wrapper class:
HashSet<Integer> temp_XList = new HashSet<Integer>(Arrays.asList(temp_X));
in Arrays.asList(temp_X); temp_X must be a Object array,not primitive type array. And HashSet<T> does not support primitive type .You have to convert each int in temp_X to Integer and add to temp_xList one by one

Can you create an array of linked lists in Java?

Is it possible to create an array of linked lists? Or an arraylist of linked lists? I've been searching everywhere and seem to be getting contradicting answers. I've seen "no" answers that state that it can't be done because you can't make an array of things that can be dereferenced. I've seen "yes" answers that state it can be done and they end there.
Thanks in advance.
If I understand you right, you basicly want to make a 2D Array, but with the second half being a linked list.
import java.util.ArrayList;
import java.util.LinkedList;
public class Test
{
public static void main(String[] args)
{
LinkedList one = new LinkedList();
LinkedList two = new LinkedList();
LinkedList three = new LinkedList();
ArrayList<LinkedList> array = new ArrayList<LinkedList>();
array.add(one);
array.add(two);
array.add(three);
// .. do stuff
}
}
Java doesn't care what the Objects in Arrays or Lists are, so there's nothing against putting another Array or List in.
The worst way: creating an array of raw List:
List[] lstString = new List[10];
for(int i = 0; i < lstString.length; i++) {
lstString[i] = new LinkedList<String>();
lstString[i].add(Integer.toString(i));
}
for(int i = 0; i < lstString.length; i++) {
for(Iterator it = lstString[i].iterator(); it.hasNext(); ) {
System.out.println(it.next());
}
}
A slightly better way: use a wrapper class that holds your List and create an array of it:
public class Holder {
List list = new LinkedList();
}
//...
Holder[] holders = new Holder[10];
for(int i = 0; i < holders; i++) {
holders[i] = new Holder();
}
Better approach: use a List<List<Data>>:
List<List<Data>> lstOfListOfData = new ArrayList<List<Data>>();
for(int i = 0; i < 10; i++) {
lstOfListOfData.add(new LinkedList<Data>());
}
I've seen "no" answers that state that it can't be done because you can't make an array of things that can be dereferenced
Doesn't matter if the array's member value is null, if you still can "access" that member, and instantiate it, it's not dereferenced.
So yes, you can.

Defining Objects in loops

im stuck with the dilemma of defining multiple objects with different names, i would like to define an amount of objects according to an amount i need taken from another part of the program
the part object(i) isnt correct, i just put it there to illustrate my problem
for(int i = 1; i <= amountOfObjectsNeeded; i++){
someclass object(i) = new someclass();
}
does anyone know how to get around this?
You should use an array in this case:
Someclass[] array = new Someclass[amountOfObjectsNeeded];
for (int i = 0; i < amountOfObjectsNeeded; i++) {
array[i] = new Someclass();
}
Note how the loop starts from 0 rather than 1--arrays in Java are indexed starting at 0.
Consider using a map, if you want to assign names/ids to your objects and access them later on by those names:
Map<String, SomeClass> map = new HashMap<String, SomeClass>();
for (int i = 0; i < numberOfObjects; i++) {
String name = getNameForObjectNr(i);
map.put(name, new SomeClass());
}
// later on
SomeClass someClass = map.get(someName); // to read an instance from the map

Categories