• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Parameterized Types in Java

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
System.out.println("Hello world!");

My name is Adrian and I'm new on this forum! From time to time, I come here for information about Java. Today is different because not only do I want to read but also interact with everyone here  . The following is my question:

I'm learning about stacks (ADT) with Interfaces and I understand how they work with the basic methods push(), pop(), and top(). What I'm trying to understand is how the parameterized type works.

For example, the class:



has the <T> which means that the class is of the Generic Type correct?

Now, if I create a demo class:



then to instantiate the class Example1 I should do the following:



if I were to use strings correct? But what if I have a stack of books (blue, yellow, and green) and they need to be placed on their respective stacks (blueStack, yellowStack, and greenStack)? Does the type <String> still applies or should I create the <Book> type for example?


 
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Adrian Meneses wrote:. . . I'm new on this forum!

Welcome to the Ranch as a more active participant.

From time to time, I come here for information about Java.

Of course, we don't know about you until you ask a question.

. . . I'm learning about stacks (ADT) with Interfaces and I understand how they work with the basic methods push(), pop(), and top().

I thought you used push pop and peek; you obviously have been given a different naming convention.

What I'm trying to understand is how the parameterized type works. . . .

At the very simplest, your class has variables declared as type T, which you would know about if you wrote the class yourself. If you downloaded the class from elsewhere, like this class, which comes with the standard Java® installation, you wouldn't see where the Ts are.
What happens is that everything put into a T field is converted by the javac tool to type Object. Every time you put a T in , it is converted to Object and whenever you get it out, the javac tool imputes a cast. But the compilation process ensures that cast will always succeed.
So, you have a Stack<T>. You declare it as a Stack<String>, and every time you try to put a String into that class, the compiler is quite happy. If you try to put a Book into that class, it won't go and it won't come out. Because (as you said) it is now a generic class and it won't even compile if you try to put a Book into it. That is the idea behind generics: in the old days we had to create a List and could put any type of Object into it; if we put a Book into a List we thought contained Strings, we had to cast it:-
String text = (String)myList.get(123);
And the program would crash with an Exception if it was a Book. So the compiler will only allow you to put Strings into your Stack<String> and it is therefore confident that you will get Strings out. No need for the cast any more; the compiler does all that for you confident that only Strings will ever come out and there is no risk of such errors.
Watch this space: more to come.
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Old way to do it (pre‑2004):-What if the book was added in a different location? What if the casts are applied to the wrong types? Why on earth would you want a List of different types like that anyway? I am sure there were lots of complaints on the lines of

C++ had generics and Eiffel has generics; why do we have to put up with such unreliable code?

So we have the newer Java5 version (2004‑2009) with generics.Now, the casts have gone, but lines 6 and 9 won't compile any more. Generics means you no longer have Lists of different types. The book will have to go in another List. The following will compile and run happily in Java5:-Different Lists for the different types. So yes, if you want to put Books into your Stacks, you need a separate object declared as Stack<Book>. The post‑2009 version of the code (Java7/8/9) is slightly different, the only difference being on lines 1 and 2:-I suggest you have a look at the Java™ Tutorials which has at least two sections about generics: 1 2.

Also find the mistake in my code. It wasn't intentional.
 
Adrian Meneses
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:
So, you have a Stack<T>. You declare it as a Stack<String>, and every time you try to put a String into that class, the compiler is quite happy.


Thank you for the explanation Ritchie! I understand now that if I declare a <String> then a string can only be pushed into the class. This leads me to a problem now: I have to ask the user to enter some information to sort books for example, but the depending on the user's input, the program must place the book into the appropriate stack. For example, if the user enters 3 books are red, 2 books are blue, and 2 books are green, then the push() method should place those books into the redBookStack[], blueBookStack[], and greenBookStack[] accordingly.

My code is as follows:



From the Demo class:


How do I check where to put the books in the appropriate stack?

Lastly, is the mistake in your code in line 7?
 
Sheriff
Posts: 7125
184
Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You wouldn't want to put a push method in your Book class.  What does pushing have to do with Books?  The push method should be in your MyStack class (if you're writing one), or just use an implementation of Deque.  (The Stack class is out of date.)
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Good 'ol Charlie Brown went to the Library and asked for a book. When the librarian asked what sort he would like, he said, “A blue one.”

There is something strange about your requirements, but it is conceivable that you could have a stack of books all the same colour of cover on your table in real life. You could consider a special stack class which sorts books into separate internal stacks by colour. That class could have Stacks<Book> as private fields. You can create a pushByColour() method and that method can sort the books. As I said it is a very unusual requirement. It also depends how you are recording the colours.
 
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Having a "stack" of books that somehow separates and sorts items into different internal stacks based on an item's characteristics makes zero sense to me.  What are the semantics of the pop() and top()/peek() methods then? If I push(redBook), push(greenBook), push(blueBook), what are pop() and top()/peek() supposed to return? blueBook? That doesn't seem logical since each of the internal color-specific stacks have a book on top. So now are you going to track the order that each internal stack was accessed as the items on the "outside facing" stack are pushed/popped? Sorting and stacking are orthogonal so the problem statement doesn't make sense to me at all.

@OP, can you post the original problem statement? Maybe you're misunderstanding what you're being asked to do.
 
Adrian Meneses
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you for responses!

I hope I can word this properly so here it goes: There is a pile of books, which needs to be sorted. If I grab a book from the pile, I will see the the author is "John" and the language of the book is "English". In that case, the book will go to a stack named English books. I grab another book and see that the author is "Victor" and the language of the book is "Spanish". In this case, the book will go into the Spanish stack.
I created a class named:
with its corresponding setter and getter methods. Now, I understand that I needed a class named MyStack where I would declare a stack and the index:

and I would use the push method in this class to push the books correct? Then, in the demo class I would create two references "englishBooks" and "spanishBooks" that would store the input from the user, create an object and then push that object to the stack. Am I correct with all of this?
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm still not clear on your intent. Why you think you need to use stacks to sort the books? Are you just making this problem up or was it given in book or by a teacher as an assignment?

Stacks are used for Last-In-First-Out operations, like when you want to process a mathematical expression that has well-defined orders of precedence. The kind of sorting you describe doesn't require the use of stacks specifically. You could accomplish the same thing with two lists, for example. What exactly does using stacks give you?
 
Knute Snortum
Sheriff
Posts: 7125
184
Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why is the class Book parameterized?  What would T be for a Book?  Do you use T in the Book Class?  What does BookInterface look like?  Why do you need to implement it in MyStack?
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'll give you an analogy to illustrate my point of confusion.  If you said you had a basket of bananas and oranges that you wanted to sort so that you could separate the bananas from the oranges, I would think that you would only need to get at least another basket. You would put all the bananas in the other basket and keep all the oranges in the first basket.  But you're saying you specifically need two wheelbarrows to sort these fruits.  So, I would be wondering, "Why the heck does he think he needs wheelbarrows instead of just baskets?"
 
Adrian Meneses
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Knute Snortum wrote:Why is the class Book parameterized?  What would T be for a Book?  Do you use T in the Book Class?  What does BookInterface look like?  Why do you need to implement it in MyStack?


I know you guys help a lot but you don't solve assignments or homework for people that have issues. The assignment read that there is a pile of books with many authors and some are written in English while other books are written in Spanish. The rest, are written in another language. I have to create an Interface, in this case BookInterface, that will be implemented by the MyStack class where the methods push(), pop(), and peek() will be. Then, the Book class will have the setAuthor(), setLanguage() with the toString() method. after that, I have to ask the user to enter the information from the first book (let's say the author is Charles Dickens and is in English) then I will use this information to put the first book from the pile in the stack of English books. If the information from the second book says that the author is Pablo and the book is written in Spanish, then the book will be placed in the Spanish stack. If the third book is by Hamil and is written in Portuguese, then the Portuguese stack will be used. <T> would be Strings? I can post my code from the Interface, Book, and Demo so you can see what I'm doing or trying to do.
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That looks as though you need a way of enumerating languages. How much do you know about enumerated types? There is a lot in the Java® Language Specification about them, too.
 
Knute Snortum
Sheriff
Posts: 7125
184
Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You don't need parameterization to do what you're describing, just three instances of MyStack.  If you wanted to -- and it might be a good idea -- you could parameterize MyStack so that it could hold Books or Clocks or Chickens or whatever, but you don't need to do that to have a stack of English, Spanish, and Other language Books.
 
Adrian Meneses
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Knute Snortum wrote:You don't need parameterization to do what you're describing, just three instances of MyStack.  If you wanted to -- and it might be a good idea -- you could parameterize MyStack so that it could hold Books or Clocks or Chickens or whatever, but you don't need to do that to have a stack of English, Spanish, and Other language Books.


I think I have to use the parameterize stack to learn how it works. And as you said it, I can put books, chickens, or clocks but the example I gave was red book, blue book, and green book. Thank you for the help. I solved that problem and ran into another one but I want to try and solve it on my own. If I can't, I'll ask for some guidance.
 
Adrian Meneses
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:That looks as though you need a way of enumerating languages. How much do you know about enumerated types? There is a lot in the Java® Language Specification about them, too.


I didn't know about that data type. I read about it and it might be useful for some applications. Are enum types only Strings?
 
Marshal
Posts: 28177
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Adrian Meneses wrote:

Campbell Ritchie wrote:That looks as though you need a way of enumerating languages. How much do you know about enumerated types? There is a lot in the Java® Language Specification about them, too.


I didn't know about that data type. I read about it and it might be useful for some applications. Are enum types only Strings?



No, they aren't "only Strings". In fact they aren't Strings at all. If you have the time and interest, go through the tutorial which Campbell linked to.
 
Adrian Meneses
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I can't figure out where the problem is to push() and print the top() of the stack (or peek() as it is known). This is, in order, my code:
This is the interface:

This is my Stack class that implements the interface:

This is the Book class

This is the book demo class:
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You're getting the output of Object.toString() because you didn't override it in your Books class.  By the way, classes like Books should have a singular name. An instance of the class only represents ONE book, right? So why would you write code that reads like "I'm going to create one books." ?
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A couple of other things:

1. Your push() logic looks faulty to me. Seems like you would get an ArrayIndexOutOfBoundsException on the very first call to push() a Book unto a new Stack Never mind, I see you did the increment and use of the index in two different statements. That's not how it's normally coded though. You wouldn't initialize the index of a new stack to -1 but 0. Then do the post increment at the same time you're accessing your stack array.

2. You declared the myBookStack variable as Stack not StackInterface. What's the point of declaring and implementing StackInterface if you're not going to use that abstraction?
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Adrian Meneses wrote:. . . I didn't know about that data type. I read about it and it might be useful for some applications. . . .

If you can remember how to find a wayback machine, find the version of the Java™ Tutorials about enumerated types from the year 2005. Even the current version tells you that Java® enumerated types are much more powerful than their counterparts in some other languages. You can give elements of an enum fields and methods, though you shou‍ld probably regard them as immutable and make sure never to try to change their state (and give them private constructors). Anywhere you can use a limited number of distinct objects, think enum. They are very useful things.Since Strings are immutable, there is no need to take defensive copies but traps are probably advisable to stop them eating the cheese off your motherboard.
 
Adrian Meneses
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Junilu Lacar wrote:A couple of other things:

1. Your push() logic looks faulty to me. Seems like you would get an ArrayIndexOutOfBoundsException on the very first call to push() a Book unto a new Stack Never mind, I see you did the increment and use of the index in two different statements. That's not how it's normally coded though. You wouldn't initialize the index of a new stack to -1 but 0. Then do the post increment at the same time you're accessing your stack array.

2. You declared the myBookStack variable as Stack not StackInterface. What's the point of declaring and implementing StackInterface if you're not going to use that abstraction?


Hi again!
I asked my professor as to why we are initializing the index as -1 and he said it could be initialized as 0 or any other number as long as I keep track of the index I am working. Regarding the implementation of myBookStack instead of StackInterface is because we are taking it slow, the class in beginning to see why we should use ADT. More importantly, I now understand why I need to declare an Interface in the demo class.

Finally, I have a question about printing queues with nodes (using the toString() method) but should I open another thread? And is there a way to mark this one as solved?
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, please start another thread if the subject is different from this one.

I have marked this thread as resolved for you. Thanks.
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
FYI, here's how an array-based Stack is usually coded (note how size is used instead index, and how it is managed):

A few caveats about the above implementation: If you don't want your Stack to accept null values, you would add an additional guard clause in the push() method. That would actually make it more consistent with the peek() implementation shown, otherwise you'd have to write more code to check if peek() returned null because the stack was empty or because that was what was pushed before.
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Two more things:
  • 1: Before popping something it will be necessary to null out the location in the array, otherwise you are risking a hard reference to an object no longer required.
  • 2: As an alternative to throwing an exception when the array is full, it is possible to copy the entire contents into a larger array.
  •  
    Junilu Lacar
    Sheriff
    Posts: 17644
    300
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Ah, yes, I forgot about the memory leak problem. Thanks for pointing that out, Campbell. And, yes, your implementation looks correct to me.
     
    Adrian Meneses
    Greenhorn
    Posts: 18
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:Two more things:

  • 1: Before popping something it will be necessary to null out the location in the array, otherwise you are risking a hard reference to an object no longer required.
  • 2: As an alternative to throwing an exception when the array is full, it is possible to copy the entire contents into a larger array.

  • I caught that too, where the element is not removed or deleted from the array. A bit confusing at the moment for me to see array[size] instead of array[index] but it will get better with time. Also, Junilu coded, on line 27, elements[size++] = element; but since the array defaults at 0, wouldn't that put the element at index 1 instead of 0? Or when he comments that the size of the array defaults to 0 he means that is defaults to null?
     
    Junilu Lacar
    Sheriff
    Posts: 17644
    300
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    size is declared as an int and because it is an instance member, it is initialized to 0. Only object references are initialized to null.

    The expression size++ uses post-increment so it will evaluate to the current value of size. Only after the current value is used will size become one more than it was before. It is equivalent to writing
     
    There's a way to do it better - find it. -Edison. A better tiny ad:
    a bit of art, as a gift, the permaculture playing cards
    https://gardener-gift.com
    reply
      Bookmark Topic Watch Topic
    • New Topic