Defining Objects in loops - java

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

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();
...
}

Get a list outside a loop

I need to get a list from another list so here is what I have done :
ArrayList<String> userList = user.getListSalarieByManager(login);
ArrayList<DHDemande> demandesList;
for (int i = 0; i < userList.size(); i++) {
demandesList = d.getDemandesForManager(userList.get(i));
}
Then I need to get the data from the list demandesList but I can't get this list outside the loop because this not have been initialized.
How can I get the data from the list inside the loop ?
That is because you haven't actually initialized your second list.
ArrayList<DHDemande> demandesList;
Should be:
ArrayList<DHDemande> demandesList = new ArrayList<DHDemande>();
By the way, the way your loop is set up sets the entire demandesList every iteration. Are you perhaps looking for List#add?
Edit: to answer you question in the comments:
Yes, you can add a list to another list using ArrayList#addAll - that would look like this:
ArrayList<String> userList = user.getListSalarieByManager(login);
ArrayList<DHDemande> demandesList = new ArrayList<DHDemande>();
for (int i = 0; i < userList.size(); i++) {
demandesList.addAll(d.getDemandesForManager(userList.get(i)));
}
Edit 2: just a small note, you can replace your for loop with a for-each, since you don't really need to know the value of i (index).
Example:
for (int i = 0; i < userList.size(); i++) {
demandesList.addAll(d.getDemandesForManager(userList.get(i)));
}
Turns into:
for (String user : userList) {
demandesList.addAll(d.getDemandesForManager(user));
}
You only need to initialize the list properly, inside or outside the loop,
but it appears that you want to add elements to the list inside the loop.
I changed your iteration over the loop to the modern java list iteration style.
// initialize variables just so this example compiles
UserProvider user = new UserProvider();
Object login = null;
DHDemandeProvider d = new DHDemandeProvider(); only
ArrayList<String> userList;
userList = user.getListSalarieByManager(login);
ArrayList<DHDemande> demandesList = new ArrayList<DHDemande>(); // construct list
for (String u: userList) {
demandesList.add(d.getDemandesForManager(u)); // add elements to list
}

Java Creating Objects at Runtime in a For Loop

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();
}
}

Using a string to write to an array

Attempting to tidy up code, originally I was using this method of writing to arrays, which is ridiculously long when I have to repeat it 20 times
if (ant.getAntNumber() == 3)
{
numbers3.add(ant.getCol());
numbers3y.add(ant.getRow());
}
if (ant.getAntNumber() == 4)
{
numbers4.add(ant.getCol());
numbers4y.add(ant.getRow());
}
I attempted to use a for loop to do it but I cant figure out how to add to the array using the string value, because it thinks its a string rather than trying to use the array
for (int j = 0; j<maxAnts; j++)
{
String str = "numbers" + j;
String str2 = "numbers" + j + "y";
//this part doesnt work
str.add(ant.getCol());
}
Any suggestions would be helpful
In Java, you cannot use the value of a String object to reference an actual variable name. Java will think you're attempting to to call add on the String object, which doesn't exist and gives you the compiler error you're seeing.
To avoid the repetition, you need to add your Lists to two master lists that you can index.
In your question, you mention arrays, but you call add, so I'm assuming that you're really referring to Lists of some sort.
List<List<Integer>> numbers = new ArrayList<List<Integer>>(20);
List<List<Integer>> numbersy = new ArrayList<List<Integer>>(20);
// Add 20 ArrayList<Integer>s to each of the above lists in a loop here.
Then you can bounds-check ant.getAntNumber() and use it as an index into your master lists.
int antNumber = ant.getAntNumber();
// Make sure it's within range here.
numbers.get(antNumber).add(ant.getCol());
numbersy.get(antNumber).add(ant.getRow());
How about this?
Ant[] aAnt = new Ant[20];
//Fill the ant-array
int[] aColumns = new int[aAnt.length];
int[] aRows = new int[aAnt.length];
for(int i = 0; i < aAnt.length; i++) {
aColumns[i] = aAnt[i].getCol();
aRows[i] = aAnt[i].getRow();
}
or with lists:
List<Integer> columnList = new List<Integer>(aAnt.length);
List<Integer> rowList = new List<Integer>(aAnt.length);
for(Ant ant : aAnt) {
columnList.add(ant.getCol());
rowList.add(ant.getRow());
}
or with a col/row object:
class Coordinate {
public final int yCol;
public final int xRow;
public Coordinate(int y_col, int x_row) {
yCol = y_col;
xRow = x_row;
}
}
//use it with
List<Coordinate> coordinateList = new List<Coordinate>(aAnt.length);
for(Ant ant : aAnt) {
coordinateList.add(ant.getCol(), ant.getRow());
}
A straight-forward port of your code would be to use two Map<Integer, Integer> which store X and Y coordinates. From your code it seems like ant numbers are unique, i.e., we only have to store a single X and Y value per ant number. If you need to store multiple values per ant number, use a List<Integer> as value type of the Map instead.
Map<Integer, Integer> numbersX = new HashMap<Integer, Integer>();
Map<Integer, Integer> numbersY = new HashMap<Integer, Integer>();
for(Ant ant : ants) {
int number = ant.getAntNumber();
numbersX.put(number, ant.getCol());
numbersY.put(number, ant.getRow());
}

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.

Categories