I'm having difficulty in creating multiple objects in a for loop the object keeps being overwritten each time the loop is run.
for(i = 0 ; i < 10; i++){
Driver one = new Driver();
}
How do I make it so that new objects are created every time the loop is run, currently one just keeps being overwritten.
Sorry for the basic question i'm just new to programming.
You can do this using array:
int n = 10;
Driver[] driverArray = new Driver[n];
for(int i = 0 ; i < n; i++){
driverArray[i]= new Driver();
}
In your code, you are declaring a local reference to Driver class, and creating new Driver object in every iteration.
It doesn't work for two reasons:
1. You are declaring local reference in for-loop so the only place, when you can use it is this for-loop.
2. Even if you declare the reference outside the loop you would initialize it with new Driver object so after loop you would have the only one Driver insance - the last one.
For more about arrays you can read here.
Hope it helps.
Related
I have a for loop like and an ArrayList as follow:
List<VehicleImpl> vehicles = new ArrayList<VehicleImpl>();
for(int i = 0; i < input.getNoVehicles(); i++) {
//Name vehicle by index
VehicleImpl vehicle = VehicleImpl.Builder.newInstance("vehicle " + String.valueOf(i+1))
//The first location - depot location is indexed as 0 in Matrices
.setStartLocation(Location.newInstance(i))
.setBreak(lunch)
.setLatestArrival(input.getOperating())
.setType(type)
.build();
vehicles.add(vehicle);
}
So, I want to ask: Is there any way I instantiate the VehicleImpl outside the loop and use the ONLY ONE instance. For each iteration, I modify the instance add the new version of instance to the list.
Yes but you have to clone the first intance at leat (By using BeanUtils for example).
Then you just update the startLocation attribute.
You could instantiate the builder outside the loop, which would halve the number of objects you're creating, but only if you were to change the builder's constructor to have zero arguments, moving the vehicle name into a setter. For example:
List<VehicleImpl> vehicles = new ArrayList<VehicleImpl>();
VehicleImpl.Builder builder = VehicleImpl.Builder.newInstance();
for(int i = 0; i < input.getNoVehicles(); i++) {
VehicleImpl vehicle = builder
//Name vehicle by index
.setName("vehicle " + String.valueOf(i+1))
//The first location - depot location is indexed as 0 in Matrices
.setStartLocation(Location.newInstance(i))
.setBreak(lunch)
.setLatestArrival(input.getOperating())
.setType(type)
.build();
vehicles.add(vehicle);
}
This is somewhat more error prone because values in the builder are not reset on each new iteration. That's not necessarily a problem for you right now, but if you were to add conditional logic, you'd probably start having a lot of problems. However, if your goal is to reduce the number of objects created, this will satisfy that.
This question might appear trivial, but I am unable to find a solution to this problem for a few days.
Snippet 1 :
for(int i = 0; i < arr.length; i++){
arr[i] = new Bucket();
}
Snippet 2 :
Arrays.fill(arr, new Bucket());
Code with snippet 1 is executing as expected, but code that includes snippet 2 is not passing all the test cases.
I am expecting both the statements to do the same work internally. But the test cases show it is not. Any help to clarify this will be very helpful.
Think about what they do: in the loop you create a new object on every iteration. In the second you create one object and fill the array with it. They are totally different.
From documentation:
Assigns the specified Object reference to each element of the specified array of Objects.
Arrays.fill() uses the same object all time:
public static void fill(Object[] a, Object val) {
for (int i = 0, len = a.length; i < len; i++)
a[i] = val;
}
So entire array becomes filled with a single instance created once by new Bucket()
I am expecting both the statements to do the same work internally.
Snippet 2 is only creating one Bucket, and adding the same instance to every slot. So they are not the same, in Java 8+ you could use a lambda and something like
IntStream.range(0, arr.length).forEach(x -> arr[x] = new Bucket());
to fill the Bucket[] arr.
I'm doing a multithreaded Java optimization algorhithm which initiates various instances of the same subclass, for time improvement reason. This subclass have itself other subclasses.
The algorhthm searchs though the search space for an optimal solution, by means of random movements. So, if i run several instances of it, i should take advantage of my system's cores and improve the search widing the search space.
I've noticed that the first instance runs well, but others seems to share the running objects of the first, picking the information they hold, even when it has finished.
Thats not what i want; i want any of the instances be insulated for the others.
I'm using Executor Services:
Code:
ExecutorService executorService = Executors.newCachedThreadPool();
ExecutorCompletionService<float[][]> service = new ExecutorCompletionService<float[][]>(executorService);
IteratedGreedy[] ig = new IteratedGreedy[instances];
Future<float[][]>[] future = new Future[instances];
// launching instances:
for (int i=0; i<instances; i++)
{
path = "\\" + i + ".txt";
ig[i] = new IteratedGreedy(path);
future[i] = service.submit(ig[i]);
}
// retrieveing solutions:
for (int i=1; i<instances; i++)
{
solutions[i] = future[i].get();
}
As you may think, the IteratedGreedy function has its own sublcasses inside.
Any help is appreciated.
Problem is, somewhere in the code, theres a class with a global static variable:
static float[][] matrix;
And then, a method uses it:
SomeMethod()
{
int f = matrix[i][b];
}
The solution is to change the way the method obtains the object:
float[][] matrix;
SomeMethod(float[][] matrix)
{
int f = matrix[i][j];
}
Hi i am trying to add the values to list as show in below code. i am getting error.
if i use like below
for (String n2 : number ) {
List<String> ARRAY = new ArrayList<String>();
if (!ARRAY.contains(n2)) {
Email(n2);
ARRAY.add(n2);
}
}
if i am using above. Though already email sent with value n2 again it is sending again. For first it has to sent but for second time n2 should be in array but still it sending. any one help. if n2 is passed to email second time it should not pass.
I am re-posting question as pervious one seems not clear i guess.
You need to move the ARRAY outside of the for loop
List<String> ARRAY = new ArrayList<String>(); // maybe as a class field
for (String n2 : number ) {
if (!ARRAY.contains(n2)) {
Email(n2);
ARRAY.add(n2);
}
}
List<String> ARRAY = new ArrayList<String>();
This line needs to be outside of your loop.
Why?
Simple. It's an issue of scope. Scope is the the lifetime and accessibility of a variable. In this case, you declare it inside of a loop, so the scope of that variable is, you guessed it, the loop. When the loop exits, the variable is destroyed.
You need to move it outside, so that the variable persists for the lifetime of the loop.
Extra Reading
Please, read the Java Naming Conventions.
Using Java 1.6 and the AtomicLongArray, I'd like to "copy" the original AtomicLongArray into a new one. There is a constructor that takes an array (AtomicLongArray(long[])), so I thought I could just get the array from the original one and give it to the constructor.
Sadly, the actual long[] in the AtomicLongArray is private and there seem to be no getters for it. Is there any way to do this, meaning copy the values from one AtomicLongArray to another? I can't create my own class based on this class, as the sun.misc.Unsafe class is not available to me.
This is needed because I'm going to iterate over the values, and I don't want them modified by another thread during iteration. So I thought I could make a copy and use that for the iteration...
Thanks!
Phillip
I suspect you have to create your own long[] and populate it first, or just iterate over the original:
AtomicLongArray copy = new AtomicLongArray(original.length());
for (int i = 0; i < copy.length(); i++)
{
copy.set(i, original.get(i));
}
Note that although each individual operation in AtomicLongArray is atomic, there are no bulk operations - so there's no way of getting a "snapshot" of the whole array at time T. If you want that sort of behaviour, I believe you'll need to use synchronization.
This data structure allows concurrent updates to individual entries in the collection. There is not overall lock, so you can't prevent another thread changing the contents while you are iterating over it.
If you need this, you need a workaround, e.g. copy the array and loop again to check it hasn't changed. If changed, repeat. Or you need a collection which supports a global lock.
long[] copy = new long[original.length()];
boolean changed = true;
// repeat until we get an unchanged copy.
while(true) {
for (int i = 0; i < copy.length(); i++) {
long l = original.get(i);
changed |= copy[i] != l;
copy[i] = l;
}
if (!changed) break;
changed = false;
}
This is not completely safe, but may be enough for what you need.