Home > front end >  How can I print an Object of a Vector when this last is into a Main-Vector?
How can I print an Object of a Vector when this last is into a Main-Vector?

Time:04-15

How can I print a Vector that is into a Vector (main). I made a program that contains a vector of stacks (java.util), inside the package I have two classes: -Stack, -mainProgram; The Stack class will create the object though a Vector (java.util) with the following methods: pop,push,peek,isEmpty,search,print. I did everything but I don't know how to print the stack contained in the Vector (main) with Its elements, where I should be able to add,remove,search and print the stacks.

Example of what I mean:

The print of the stacks that I wanna print should be like this -->


Stack 1:
10
20
30
40
50
60
Stack 2:
1
2
3
4
5

Stack 3:
100
110
120
130

Do you have any advice?

CodePudding user response:

You shouldn't be using Vector anymore since it has become a legacy class years ago.

If you need to implement a Stack with a data structure of the Collections framework, then an ArrayDeque is your best choice.

This class is likely to be faster than Stack when used as a stack

However, if using a Vector is a constraint, you can simply print your elements with two nested fors. I've assumed that your innermost Vector contains Strings.

public void print(Vector<Vector<String>> vet){
        int i = 0;
        for (Vector<String> v : vet) {
            System.out.printf("Stack %d:%n",   i);
            for (String s : v) {
                System.out.println(s);
            }
            System.out.println();
        }
}

The implementation with an ArrayDeque would be exactly the same

public void print(ArrayDeque<ArrayDeque<String>> vet){
        int i = 0;
        for (ArrayDeque<String> v : vet) {
            System.out.printf("Stack %d:%n",   i);
            for (String s : v) {
                System.out.println(s);
            }
            System.out.println();
        }
}
  • Related