This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 6 years ago.
I have a simple class with only one String field and I have ArrayList.
When I do for loop to add some elements to ArrayList something strange happeneds.
ArrayList<MyClass> list = new ArrayList<Myclass>();
MyClass mc = new MyClass();
for(int i=0;i<someNumber;i++){
String s = new String(Integer.toString(i));
mc.setString(s);
list.add(mc);
}
After this, when I print my list, the string for every element from the list is same.
I understand that if I do list.add(new Myclass(s); works correctly but do I need to create a new instance of MyClass every time? If someNumber is large it takes too much memory. Thanks
You are re-adding the same element to the list. Try:
List<MyClass> list = new ArrayList<>(someNumber);
for(int i=0;i<someNumber;i++){
String s = new String(Integer.toString(i));
MyClass mc = new MyClass(); // create new object mc
mc.setString(s);
list.add(mc); // add the new object to the list
}
By the same object I mean the same pointer to the object, you must create new pointer (initialize new class) to add it to the list as separate instance. In this case you were setting different value in setString on the same object and multiplicating the object in the list.
You need to move the instantiation of the object mc inside the loop.
ArrayList<MyClass> list = new ArrayList<Myclass>();
for(int i=0;i<someNumber;i++){
MyClass mc = new MyClass();
String s = new String(Integer.toString(i));
mc.setString(s);
list.add(mc);
}
Related
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.
I'm trying to add a string to an array of array lists.
ArrayList<String>[] test = (ArrayList<String>[]) new ArrayList[2];
test[0].add("Hello World!");
When the code above is executed, a null pointer exception is thrown. Any ideas how this can work?
Your code is null pointering because array 'test' only contains a null references of type ArrayList. Your construction only creates the array storage, not the list storage. This is important to understand and is the same for any array of Objects (or Collection of Collections).
For example the following will contain 3 cells all which contain null.
Integer[] foo new Integer[3]
You need to instantiate a list before you can add to it.
ArrayList<String>[] test = (ArrayList<String>[]) new ArrayList[2];
test[0] = new ArrayList<String>();
test[0].add("Hello World!");
For creating an array of ArrayList. You have to do the following
ArrayList[] test = new ArrayList[2];// create array with all elements null
for(int i=0; i<2;i++)
{
test[i] = new ArrayList<String>(); // initialize each element with ArrayList object
}
test[0].add("Hello World!");
you are using wrong syntax
it should work like this
ArrayList<String>[] arrayList = new ArrayList[2];
arrayList[0] = new ArrayList<String>();
arrayList[0].add("Hello World");
You should create a new array each time when you are trying to add into the list,
String[] test= new String[2];
ArrayList<String[]> test= new ArrayList<String[]>();
t2[0]="0";
t2[1]="0";
test.add(t2);
in the example above you are passing the reference of the test array object to the list.On each .add() method
or same thing can also be done in the below way in a single statement,
ArrayList<String>[] test = (ArrayList<String>[]) new ArrayList[2];
test.add(new String[] {"0", "0"});
Update
If you are trying to create array of arraylist have look here ,
Create an Array of Arraylists
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++;
}
This question already has answers here:
How to add new elements to an array?
(19 answers)
Closed 8 years ago.
Im a beginner to Java and I'm trying to create an array of a custom class.
Let say I have a class called car and I want to create an array of cars called Garage. How can I add each car to the garage? This is what I've got:
car redCar = new Car("Red");
car Garage [] = new Car [100];
Garage[0] = redCar;
If you want to use an array, you have to keep a counter which contains the number of cars in the garage. Better use an ArrayList instead of array:
List<Car> garage = new ArrayList<Car>();
garage.add(redCar);
The array declaration should be:
Car[] garage = new Car[100];
You can also just assign directly:
garage[1] = new Car("Blue");
If you want to create a garage and fill it up with new cars that can be accessed later, use this code:
for (int i = 0; i < garage.length; i++)
garage[i] = new Car("argument");
Also, the cars are later accessed using:
garage[0];
garage[1];
garage[2];
etc.
Hello I have to add elements to my list and I notice if I Use the method add I just add the reference to my list but I would like to add the elements and not the reference:
ArrayList ArrayListIdle = new ArrayList();
List<State> arrayState = new ArrayList<State>();
while(rs.next){
state = new State();
state.updateStateArray(arrayState);//This function mods the elements of (arrayState);//This
state.setArrayStates(arrayState);//add a list of arrayState to the object state
//I have a array and I want to add the element state with his arraylist(not the reference to)
ArrayListIdle.addAll(state);
// I tried with add , but in the next iteration the arrayState change.
}
You are adding the same ArrayState object every time. You should create a new ArrayState object every time in the while loop to avoid it getting changed every time. This is because by default objects are always passed by reference in Java.
Try doing this:
ArrayList arrayListIdle = new ArrayList();
while(rs.next){
state = new State();
List<State> arrayState = new ArrayList<State>();
state.updateStateArray(arrayState);//This function mods the elements of (arrayState);//This
state.setArrayStates(arrayState);//add a list of arrayState to the object state
arrayListIdle.addAll(state);
}
The problem here is that you have one "arrayState" object and all of the state objects reference the same one.
One way to solve that here is to move the object creation inside loop so that a different object is created every time.
while(rs.next) {
List<State> arrayState = new ArrayList<State>();
...
}