Coldoe
Coldoe

Reputation: 71

Print List in Java

I'm newbie in Java. I'm not sure why line my2.print_list(); is printing only object my2. I want to print every time whole list of objects. I'm adding every object to list in constructor. I'm 90% sure that for loop in function print_list is good. The compiler shows no problems. I'll appreciate all help.

public class Main {

        public static void main(String[] args) {
        // write your code here
           rectangle my = new rectangle(5);
           rectangle my1 = new rectangle(3,6);
           rectangle my2 = new rectangle(10,7);

           System.out.println( my2.getCounter());
           my2.print_list(); ////////////////////<- described line

        }
    }

/// my class rectangle

    import java.util.ArrayList;
    import java.util.List;

    public class rectangle {
        public static int counter =0;
        public int x;
        public int y;
        public List<rectangle> List = new ArrayList<rectangle>();

        public rectangle(int x, int y) {
            this.x = x;
            this.y = y;
            System.out.println("Rec");
            List.add(this);
            counter++;
        }
        public rectangle(int x) {
            this.x = x;
            this.y = x;
            System.out.println("Sqr");
            List.add(this);
            counter++;
        }

        @Override
        public String toString() {
            return "x->"+x+" y->"+y+" Field: "+(x*y);
        }

        public void print_list()
        {
            for(rectangle x : List)
            {
                System.out.println(x);
            }
        }

Upvotes: 0

Views: 2620

Answers (2)

nicomp
nicomp

Reputation: 4657

Change

public List<rectangle> List = new ArrayList<rectangle>();

to

public static List<rectangle> List = new ArrayList<rectangle>();

So there's only one instance of List.

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201527

Every instance of your class has its' own instance of List. Make it static if it should be shared (which is the only way your List will be populated). Also, please rename the variable List (it looks exactly like the interface java.util.List). Also, there's no reason to make it public.

private static List<rectangle> myList = new ArrayList<rectangle>();

And then change print_list like

public void printList()
{
    for(rectangle x : myList)
    {
        System.out.println(x);
    }
}

Also, the class name should be Rectangle (to follow Java naming conventions).

Upvotes: 1

Related Questions