code4Life
code4Life

Reputation: 13

Java: Last reference variable are printed out

I have a class that contains list of integer numbers. I wanted to print different sets of integer numbers. But my code prints exactly the same numbers even though the reference variables are different. Here is my code:

import java.util.ArrayList;

public class OrderedIntListUtility {
    public static void printContains(OrderedIntList list) {
        for(int i = 0; i < list.orderedIntegerList.length; i++) {
            System.out.print(list.orderedIntegerList[i]);
        }
    }
}

import java.util.ArrayList;
import java.util.Arrays;

public class OrderedIntList {
    static int[] orderedIntegerList;

    public OrderedIntList(int ... elements) {
        orderedIntegerList = elements;
    }

    public OrderedIntList() {
        orderedIntegerList = null;
    }
}

public class TestOrderedIntList {
    public static void main(String[] args) {
        OrderedIntListUtility operate = new OrderedIntListUtility();
        OrderedIntList listOfA = new OrderedIntList(2,3,1,55,77);
        OrderedIntList listOfB = new OrderedIntList(2,3,5,77);
        operate.printContains(listOfA);
        System.out.println();
        operate.printContains(listOfB);

    }
}

the problem is operate.printContains(listOfA) prints the listOfB orderedIntList. I am confused. They are of different variable names right? Please help. Thank you!

Upvotes: 0

Views: 52

Answers (1)

sol4me
sol4me

Reputation: 15708

In class OrderedIntList You have the static int[] orderedIntegerList;change it to int[] orderedIntegerList;and it will work. Static means available at the class level, not at instance level

Upvotes: 1

Related Questions