I want to add a user defined type, like the one shown below, to an ArrayList.
import java.util.ArrayList;
class MyObj
{
int iX;
}
public class testForLoopjava
{
public static void main(String[] args)
{
MyObj ob1 = new MyObj();
ArrayList<MyObj> al = new ArrayList<MyObj>();
int a,b;
for(int i =0;i<5;i++)
{
ob1.iX = i + 5;
al.add(ob1);
}
for(int j=0;j<5;j++)
System.out.println("iX: "+al.get(j).iX);
}
}
When I try to print the above code, iX always prints 9. i.e. iX is updated by the last value in the list. What is the reason for this? Am I doing some basic mistake.?
Output:
iX: 9
iX: 9
iX: 9
iX: 9
iX: 9
You're adding the same object to the list each time. You should use a fresh instance created within the loop.
e.g.-
ArrayList<MyObj> al = new ArrayList<MyObj>();
int a,b;
for(int i =0;i<5;i++)
{
MyObj ob1 = new MyObj();
ob1.iX = i + 5;
al.add(ob1);
}
Otherwise, your list will contain a list of references to the same instance and modifying that one instance affects every entry in that list.
This sort of issue is a strong argument for using immutable objects wherever possible. If you can, a good approach is to instantiate the iX field in the constructor and make it final thus not allowing it to change post-instantiation (check out the Java final keyword).
public class MyObj {
private final int iX;
public MyObj(int i) {
iX = i; // iX is initialised here but can't be changed again
}
}
This approach can yield a safer solution (wrt. the above) with the caveat that your objects can be changed post-instantiation. It sounds like a restrictive practice, but you'll be surprised to find many of your objects can be implemented in this fashion.
That's because you're always putting the same instance (the same object) in your list.
try:
public static void main(String[] args)
{
ArrayList<MyObj> al = new ArrayList<MyObj>();
int a,b;
for(int i =0;i<5;i++)
{
MyObj ob1 = new MyObj();
ob1.iX = i + 5;
al.add(ob1);
}
for(int j=0;j<5;j++)
System.out.println("iX: "+al.get(j).iX);
}
You're adding the same object multiple times to the list. You have only one MyObj created and you only change the int value that object is holding.
thats because you are keeping just one reference to MyObj and all elements refer to it. try modifying the code as follows:
for(int i =0;i<5;i++)
{
MyObj ob1 = new MyObj();
ob1.iX = i + 5;
al.add(ob1);
}
also, remove the ob1 definition outside of the loop.
You are changing the same object every time, so the last time in your loop it ill set ob1.iX = 4+5 (=9).
You should create a new instance everytime, so put it in your loop:
for(int i =0;i<5;i++)
{
MyObj ob1 = new MyObj();
ob1.iX = i + 5;
al.add(ob1);
}
One more version using Object array:
package com.may.arrays;
import java.util.ArrayList;
public class AddObjectToArray {
public static void main(String args[]){
ArrayList<MyObject> l_list = new ArrayList<MyObject>();
MyObject l_myObj = new MyObject();
l_myObj.holder = new MyObject2[6];
for(int i=0;i<5;i++){
l_myObj.holder[i] = new MyObject2();
l_myObj.holder[i].value = i+5;
l_list.add(l_myObj);
}
for(int j=0;j<5;j++){
System.out.println("value is: "+l_list.get(j).holder[j].value);
}
}
}
class MyObject{
MyObject2[] holder;
}
class MyObject2{
int value;
}
you are adding same object to list , because of this is giving same result.
you have to create new instance every time. :)
Related
In the following code, I am wondering how to use the other object. Specifically how do I get the two ArrayLists to have different values within them when I am passing them into the append method.
The following code is supposed to append two Arraylists together without modifying either of them.
I understand that in order to do this, I need to create a separate instance of the Arraylist "values", thats why I used the other object, but I am wondering how do I assign separate values to each instance of the Arraylist
package com.company;
import java.util.ArrayList;
public class MergeSequence {
public ArrayList<Integer> values;
public MergeSequence(){
values = new ArrayList<Integer>();
}
public void add(int n) {
values.add(n);
}
public String toString() {
return values.toString();
}
public MergeSequence append(MergeSequence other)
{
MergeSequence result = new MergeSequence(); // Create a new result object.
// Iterate through the "local" ArrayList and add each value to the result
for (int i = 0; i < values.size(); i++)
{
int j = values.get(i);
result.add(j);
}
// Now, iterate through the "external" ArrayList and add each value to the result
for (int i = 0; i < other.values.size(); i++)
{
int j = other.values.get(i);
result.add(j);
}
result.toString();
// Then return the result. Neither source ArrayList is modified.
return result;
}
}
toString itself doesn't output anything to std-out. So after calling result.toString(); you won't see the result in the console. You need to use System.out.println(result) to output the result.
By the way, printing the values in the append method is a side effect. It would be better to print the values outside of the append. E.g.:
public static void main(String[] args) {
final MergeSequence a1 = new MergeSequence();
a1.add(1);
a1.add(2);
final MergeSequence a2 = new MergeSequence();
a2.add(3);
final MergeSequence a3 = a1.append(a2);
System.out.println(a1); // [1, 2]
System.out.println(a2); // [3]
System.out.println(a3); // [1, 2, 3]
}
Just add a main method to test
public static void main(String[] args) {
MergeSequence m1 = new MergeSequence();
m1.add(1);
m1.add(2);
MergeSequence m2 = new MergeSequence();
m2.add(3);
MergeSequence m3 = m1.append(m2);
System.out.println(m3.toString());
}
I have created a class using linked list to display 20 Fibonacci numbers. Here is my code:
import java.util.LinkedList;
public class FibonacciLinkList {
private LinkedList<Integer> fibonacciList;
public FibonacciLinkList(LinkedList<Integer> FibonacciLinkList) {
this.fibonacciList = FibonacciLinkList;
}
public LinkedList<Integer> sum()
{
int n, a = 0, b = 0, c = 1;
for(int i = 1; i <= 20; i++)
{
a = b;
b = c;
c = a + b;
}
return fibonacciList;
}
public void display() {
System.out.println(fibonacciList);
}
public static void main(String[] args) {
LinkedList fibonacciList = new LinkedList();
fibonacciList.display(); //This is where the error is
}
}
The problem I am having is displaying the Fibonacci numbers on the console.
I have tried to do this by using a display method but it hasn't really worked for me. I have done a lot of searching online and on SO and have tried them but they have not worked for me. It would be appreciated if you could fix my code so that it does work.
I am new to linked list and this is the first time I am coding a linked list myself and I feel that a solution to this problem will help me understand linked lists better.
As I mentioned, LinkedList is not an instance of FibonacciLinkedList, and it does not possess the display() method. Attempting to invoke it on the LinkedList object will lead to failure to compile.
The sum() method is not invoked nor does it actually do anything. That is, it does not assign anything to the fibonacciList you have.
I would recommend that you extend the LinkedList class and generate the items on instantiation. Then, using the default toString() you can display to console. After all, the class is simply an extension of the LinkedList data structure to store Fibonacci numbers up to 20.
As you extend LinkedList, you inherit the AbstractCollection.toString() method for which the "string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]")."
public class FibonacciLinkedList extends LinkedList<Integer> {
public FibonacciLinkedList(int n){
int a = 0, b = 0, c = 1;
for(int i = 1; i <= n; i++) {
a = b;
b = c;
c = a + b;
this.add(c);
}
}
public void display() {
System.out.println(this.toString());
}
public static void main(String[] args) {
FibonacciLinkedList list = new FibonacciLinkedList(20);
list.display();
}
}
I fixed your code:
import java.util.LinkedList;
public class FibonacciLinkList {
private LinkedList<Integer> fibonacciList;
public FibonacciLinkList() {
this.fibonacciList = new LinkedList<Integer>();
}
public LinkedList<Integer> sum()
{
int n, a = 0, b = 0, c = 1;
for(int i = 1; i <= 20; i++)
{
fibonacciList.add(a);
a = b;
b = c;
c = a + b;
}
return fibonacciList;
}
public void display() {
System.out.println(fibonacciList);
}
public static void main(String[] args) {
FibonacciLinkList fibonacciList = new FibonacciLinkList();
fibonacciList.sum();
fibonacciList.display();
}
}
Try this.
There is several points that you need to take care :
sum() is never called.
the look in sum() does not change fibonacciList, it only uses local variables and does nothing else with it.
display() is NOT a LinkedList function, so it will likely not work. And even if it were working, it will likely not display what you expect : you need to loop through the list and print each value.
an other fibonacciList is created in the main function, so the display (if it was working) would show the content of this local list and not the global one.
I am adding five objects in the list with the help of for loop. I am initializing my object outside the for loop. In the body of for loop i am changing the object setter properties and adding it in the list. The output with this is: It will add five objects but all have the same attributes even after setting the different values for the attribute.
See the following code
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class ASD {
public static void main(String args[]) {
List list = new ArrayList<A>();
System.out.println("Before Insert List is " + list);
A obj = new A();
for (int i = 0; i < 5; i++) {
obj.setA(new Random().nextInt(10));
list.add(obj);
}
System.out.println("After Insert List is " + list);
for (int i = 0; i < 5; i++) {
A prObj = (A) list.get(i);
System.out.println("Values are" + prObj.getA());
}
}
}
class A {
int a;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
}
If I initialize A's object inside the for loop then it will add five objects and also changes the attribute for the objects. Can anyone explain this behaviour
You have created just one instance and setting it several times inside the for loop.Create a new instance of A inside the for loop, not outside it
for (int i=0;i<5;i++) {
A obj = new A();
obj.setA(new Random().nextInt(10));
list.add(obj);
}
When you are doing this -
A obj = new A();
for (int i=0;i<5;i++) {
obj.setA(new Random().nextInt(10));
list.add(obj);
you are actually adding reference to the same object after changing it's attribute setA.
That way, all of the list elements have reference to the same object (with same value of a).
You need to add new objects if you want to have different values -
for (int i=0;i<5;i++) {
obj = new A(); // new object
obj.setA(new Random().nextInt(10));
list.add(obj);
Here is my code:
class Myclass {
private static int[] array;
public static void main(String[] args) {
Myclass m = new Myclass();
for (int i = 0; i < 10; i++) {
m.array[i] = i;
System.out.println(m.array[i]);
}
}
public Myclass() {
int[] array = new int[10];
}
}
It throws a java.lang.nullPointerException when trying to do this:
m.array[i] = i;
Can anybody help me please?
You have declared a local variable array in your constructor, so you're not actually initializing the array declared in Myclass.
You'll want to refer directly to array in the constructor. Instead of
int[] array = new int[10];
Use this
array = new int[10];
Additionally, you've declared array static in the scope of your Myclass class.
private static int[] array;
You only have one instance of Myclass here, so it doesn't matter, but normally this would not be static, if you're initializing it in a constructor. You should remove static:
private int[] array;
In your constructor you are making your assignment to a local variable names array, not the static class variable also named array. This is a scope problem.
I'm also guessing that since you access array via m.array, you want a member variable and not a static one. Here's the fix
class Myclass {
private int[] array;
public static void main(String[] args) {
Myclass m = new Myclass();
for (int i = 0; i < 10; i++) {
m.array[i] = i;
System.out.println(m.array[i]);
}
}
public Myclass() {
rray = new int[10];
}
}
in MyClass() type this
this.array = new int [10];
instead of this
int[] array = new int[10];
Your code should be as below. In the constructor, instead of initializing the instance variable you created a new local variable and the instance variable was left uninitalized which caused the NullPointerException. Also the instance variable shouldn't be static.
class Myclass {
private int[] array;
public static void main(String[] args) {
Myclass m = new Myclass();
for (int i = 0; i < 10; i++) {
m.array[i] = i;
System.out.println(m.array[i]);
}
}
public Myclass() {
array = new int[10];
}
}
First, if you plan to use array as a field of m (i.e. m.array) don't declare it as static, but:
private int[] array;
Next thing you have to do is to initialize it. Best place to do that is in the constructor:
public MyClass() {
array= new int[10]; //just array = new int[10]; don't put int[] in front of the array, because the variable already exists as a field.
}
The rest of the code should work.
I have global variable private int temp=0;. In the class it is incrementing (At some what stage say it is temp=10).When again loading the class temp is still 10. But I need it 0. How can I do that?
code:
public class MyClass
{
private int temp = 0;
public void method1() // while calling this method temp increments say temp =1;
{
temp++;
}
public void method2()
{
if(temp == 0)
System.out.println("temp = "+temp):
}
}
After this suppose temp = 10, and when loading MyClass still temp=10, but I need temp=0 again. Since I'm new to programming I don't know whether it make sense.
temp is always going to be 0 unless it is declared as static.
MyClass mc = new MyClass();
mc.method1() // 'temp' of mc object is now 1
MyClass mc2 = new MyClass();
mc2.method2() //'temp' of mc2 object is still 0!
I'm not sure what you meant by loading the class, calling the class etc
Note that each new instance of the class will give you temp = 0 and If you mean within the same instance,See this example, I added a new method, method0()
public class MyClass
{
private int temp = 0;
public void method0()
{
temp = 0;
}
public void method1()
{
temp++;
}
public void method2()
{
if(temp == 0)
System.out.println("temp = "+temp):
}
}
In this case,
MyClass mc = new MyClass();
mc.method2();
mc.method1();
mc.method2();
mc.method0();
mc.method2();
Will give you,
temp = 0
//Incremented value of temp
//condition if(temp==0) fails
//reset value of temp
temp = 0
Hope this is what you meant.cheers.
If i understand your question correctly, you want to re-initialize temp to 0 every time you create a new object of the class - MyClass.
If this is what you want, then make use of a constructor. And initialise temp to 0 in the constructor.
public MyClass
{
temp = 0;
}
This way, every time you create a new object of MyClass, temp will be set back to 0.