Win a copy of Java XML & JSON this week in the XML and Related Technologies forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Devaka Cooray
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Junilu Lacar
  • Paul Clapham
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • salvin francis
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

Create my own object that works like an array  RSS feed

 
Greenhorn
Posts: 14
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a number of doubles (money (calculated by product price * quantity)) and integers (the product number ) which I want to save in a list. After saving them I want to sort them in a way that the integer-list is in ascending order and the corresponding double is still at the right place. This might look like this:
productnumber       money                                       and after sorting like this    productnumber   money

4                           3.8                                                                                    1                     4.6                    
1                           4.6                                                                                    2                      5.2
2                            5.2                                                                                   4                       3.8

First I wanted to use two Arrays and somehow reflect the changes on the indexes of the integer list on the double list
My research revealed this to be a stupid idea:
https://stackoverflow.com/questions/12824423/sort-array-and-reflect-the-changes-in-another-array

next i thought about making a mixed 2 D array.
but this post
https://stackoverflow.com/questions/5809486/java-easiest-way-to-store-mixed-data-types-in-a-multidimensional-array
told me it would be smarter to make my own object and "make it a single dimensional array".
What a chance to learn about objects! After countless youtube tutorials I now understand the concept of classes, constructors and Objects. But I cant seem to get the last bit working. Here is my Class:



In my main method I tried differrent ways of getting my object to be an array. I also tried to declare an array in my instance variables in my class "MyOwnList". It failed because I could not use one of the variables (int size) of my main code which I would need to tell Java in MyOwnList how long my Array should be.
here is the rest of my (still unfinished) code.




Just in case you are interested: Here is the task I want to solve:

A mail-order house sells five products whose retail prices are as follows:

product 1, $2.98;
product 2, $4.50;
product 3, $9.98;
product 4, $4.49;
product 5, $6.87.
Write an application that reads a series of pairs of numbers as follows: <product number> <quantity sold>. Your program should use a switch statement to determine the retail price for each product. It should calculate and display the total retail value of all products sold. Use a sentinel-controlled loop to stop looping when reading 0 as product number and display the final results.


Thanks in advance !
Louis

 
Marshal
Posts: 62801
203
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
They have given you some good advice on SO. Parallel arrays are awkward to implement and error‑prone; you are far better creating an object that encapsulates the data you want to anaylse. Then you can put them into an array.
Another thing: you will have to work out how to sort the array. Start by deciding what you are going to sort by. I don't think your products have a natural ordering, otherwise yo uwould make them implement Comparable. You can sort by price or you can sort by ID number. So look in the Java™ Tutorials for advice.

By the way: Java® only supports 1D arrays; what appear to be 2D arrays are really arrays of arrays.
You cannot implement something that behaves like an array without using an array. Arrays are built‑in features of the language with their own syntax, which cannot be directly replicated by users.
 
Campbell Ritchie
Marshal
Posts: 62801
203
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please be careful about names. You called your class MyOwnList when it doesn't represent any sort of list. It is a product, so call it Product, or similar. Use capitalLettersAsAppropriate: productNumber not productnumber and getProductNumber() not getproductnumber() please. When you get the names right, you will be able to read the code out and know what it means. Don't call a class yoyo; it should read Yoyo or YoYo and it should represent a yo‑yo. Whenever the term yoyo appears in your code, nobody will know what it means, least of all yourself. Have you tested the Product code? You may need a class to test Product. Does Product need equals() hashCode() or toString() methods? I think it won't be long before you bewail the absence of toString().
Beware of mixing terms like money and cash. You mean price, so call the field price and call the getXXX method getPrice(). Similarly in the constructor, use the term price and use the this.xxx notation, which you have used correctly so far

Why have you got a no‑arguments constructor?

Only when you have got Product working should you write any other code. I can't understand your yoyo class; I think you may end up getting rid of all that code.
 
Louis Müller
Greenhorn
Posts: 14
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:They have given you some good advice on SO. Parallel arrays are awkward to implement and error‑prone; you are far better creating an object that encapsulates the data you want to anaylse. Then you can put them into an array.



This is where I dont know what to do. How can I put them into an array? I think I already created an object that encapsulates the data didnt I?
I tried this:

halfSize is half the size of my list of Inputs.
but it doesnt work. Could you tell me how I can put the data in my object into an array? Or am I generally barking up the wrong tree here ?

Campbell Ritchie wrote:Another thing: you will have to work out how to sort the array. Start by deciding what you are going to sort by. I don't think your products have a natural ordering, otherwise yo uwould make them implement  



This I have to figure out. I still dont really know how my array will look in the end. Will it be an array of objects? More specific of an Object of my class (Which I now renamed project!)

So far I have not tested my Product class.

Only when you have got Product working should you write any other code. I can't understand your yoyo class; I think you may end up getting rid of all that code.


Since this is the first Object I ever created I dont really know whats going on in Product. I was hoping I could use it to get my program work and understand it fully when seeing it work.
My yoyo class (the name is stupid, no doubt) so far takes the Input and seperates it so I can extract the productNumber and quantity from it.
The Input looks (for example like this):

1 5  
5 10  
2 0  
0

The first number each line ist the product number, whilst the second represents the quantity of sold items.
I hope this clarifies it. Also since I just started Java a few months ago I think I dont have developed the perfect approach on problems. I usually start with getting the input in the main class and from there on I try to figure out whats going on.

Why have you got a no‑arguments constructor?  


I made this because i thought I'd need to initialize an Object without parameters first.

I know this is a mess : D
 
Bartender
Posts: 10720
68
Eclipse IDE Hibernate Ubuntu
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[A couple of my suggestions repeat what Campbell has already said]
1. Your MyOwnList class looks like a product to me, so why not just call it Product? After all, each instance is a single product, not a List.
2. getproductnumber() should be getProductNumber().
3. getCash() should be getMoney() (although I think 'price' might be a better name for the field).
The last two might seem a bit nitpicky, but naming standards are really important in Java.

4. Why not add a "constructor" to Product that takes a BufferedReader? That way all your 'creation' logic is contained in in the Product class, eg:
The one above is very crude, and will throw an Exception if the reader doesn't specifically supply an int, followed by space, followed by a double, but hopefully you get the idea.
And now you can easily populate an ArrayList of Products, viz:

Finally, I suggest you have a look at the Scanner class. It's a bit clunky, but far less clunky than using a BufferedReader for input.

Hope it helps

Winston
 
Campbell Ritchie
Marshal
Posts: 62801
203
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Louis Müller wrote:. . .
halfSize is half the size of my list of Inputs.

Well, that bit looks correct apart from the fact that you haven't explained about halving the size. Make a count of how many object there will be, not how many keyboard inputs you need.


but it doesnt work. Could you tell me how I can put the data in my object into an array? . . .

You don't put the data into the array; you put the objects into the array. You are going to have to find some way to write this sort of thing:-or you can shorten that to:-I suggest you should get the array full, with no empty spaces, otherwise you will have trouble with nulls later on.

. . .

Campbell Ritchie wrote:Another thing: you will have to work out how to sort the array. . . .

This I have to figure out. . . . Will it be an array of objects? More specific of an Object of my class (Which I now renamed project!)

So far I have not tested my Product class. . . .

Yes, it will ba an array of objects of your Product class. Test that class to make sure it is working before you try any sorting.
I don't think project is a good name, not even if you spell it Project.

. . . I think I dont have developed the perfect approach on problems. I usually start with getting the input in the main class and from there on I try to figure out whats going on.

You don't want to figure out what is going on. You want to decide what you are going to do.

Why have you got a no‑arguments constructor?  

I made this because i thought I'd need to initialize an Object without parameters first.

That will create a product object with the values (0, 0.0), which you probably don't want. I suggest you should delete that constructor altogether.

I know this is a mess : D

I think that is because you are trying to do too many things simultaneously; you will find it much easier if you sort out one problem at a time. That is why I haven't said much about the yoyo class; I am leaving that till later.
 
Winston Gutkowski
Bartender
Posts: 10720
68
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Louis Müller wrote:I know this is a mess : D

You're doing fine; just taking on an awful lot at once. And don't worry, it's quite normal when you're new to it all.

Think about what you want to do, and try and break it down into tasks:
  • How do I get an int/double from the keyboard?
  • How do I create a Product?
  • How do I add a Product to a List?
  • and only THEN
  • How do I put it all together?

  • Winston
     
    Campbell Ritchie
    Marshal
    Posts: 62801
    203
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Winston Gutkowski wrote:. . .

  • How do I get an int/double from the keyboard?
  • How do I create a Product?
  • . . .

    Good advice as usual, but I would probably create the Product objects with numbers in the code first, and only try getting those numbers from the keyboard later.

    And this means, the number of conflicting pieces of advice you get is equal to the number of people you ask
     
    Louis Müller
    Greenhorn
    Posts: 14
    IntelliJ IDE Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thanks for all the advice. I advanced a bit in my code. Before your explanations, I somehow thought I'd have to create an Object that behaves like an Array. Now I (think I) understand that I have to create an object and then put a number of those objects in an Array. Way easier to handle I guess.
    So now I'm dealing with the problem of sorting my Product.
    This is what I understood so far:
    I have to implement the Comparable Interface in my Product class. This enables me to use certain methods of this interface. In my case, the compareTo method is what I will need. I now have to write an implemantation to tell the sort() method that I will use later by what it should sort ! Is that correct?
    In order to do this I wrote the following code:



    From the extremely high level of not-understanding this code you'll be probably able to tell that I didnt come up with this myself. I found a example and tried to adjust my own project to it.

    I have yet to try if this works but I try to follow your advice and break it into tasks and Im not really sure how to test my Product without writing the rest of the code.
    But even if it were to work, I'd still ask the following questions:

    1. Will the sort method I'll use later just use the compareTo on all (or better: on as many as necessary to figure out the order) my objects?

    To my compareTo method:
    I thought this would return 0 for the objects beeing equal on the attribute I'm investigating them. If that is right:
    2. what is null ? What I understood is that it kind of means that there is no reference to an object. That doesnt make sense to me. Why do they both have to be null in order to return null? Since getProductNumber will the method the product number I thought this would compare the integer productNumber.
    Same question applies on the other 2 if's as well. When this.productNumber represents the productNumber of the object the method is currently "talking about", why does it have to be "null"? I would have expected something like Object m > this.Object?
    3. I thought with the 3 if's I would have covered all the cases. Why is there suddenly a compareTo method in my own compareTo method : D

    God damnit I hope you can fight your way through this jungle.
     
    Campbell Ritchie
    Marshal
    Posts: 62801
    203
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Louis Müller wrote:. . . . Now I (think I) understand that I have to create an object and then put a number of those objects in an Array. . . .

    That sounds correct Getting better.

    I have to implement the Comparable Interface in my Product class. This enables me to use certain methods of this interface. In my case, the compareTo method is what I will need. . . .

    In that case it should be Comparable<Product>. I thought compareTo() was the only method in that interface; have they added anything?
    Don't declare the method as taking Object as its parameter. Your method should read public int compareTo(Product other) {...

    Didn't I give you a Java™ Tutorials link yesterday? Have you read it? Implementing Comparable implies that there is one criterion according to which objects “vary in size” from objects of the same type. If there are several criteria that could be used for sorting, you want a Comparator.

    . . . . I found a example and tried to adjust my own project to it.

    Careful. You don't know how good the example you found is.

    . . . my compareTo method:
    . . . would return 0 for the objects beeing equal . . .

    Yes, that's right.

    2. what is null ? What I understood is that it kind of means that there is no reference to an object. . . .

    Yes, it means there is no reference to an object; The compareTo() method doesn't have to acept nulls. If you pass null, it will throw an exception, which I think from my reading of compareTo() is appropriate behaviour.

    God damnit . . .

    Careful about the language please.
     
    Campbell Ritchie
    Marshal
    Posts: 62801
    203
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    The good news is:- you can simply test your Product objects like this:-You will have to override the toString() method to get a sensible output. Since you haven't given Product any methods to change anything, you won't need to test those methods. You should, I think try incorrect inputs as well, but I don't think you know enough programming yet to know how to deal with a price of $−9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999.99.

    The bad news is, your assignment appears only to test your knowledge of switch statements. You are supposed to enter 6 6 which means you have bought six of product 6, so you go to the switch which gives you a price of $1.59 for No 6 and you calculate that to $9.54, which you add to the total. When you enter product No 0, your loop ends and you display the total. The assignment doesn't seem to require any knowledge about objects, and I don't think you need even to keep a record of what you ordered. Maybe you only need the total price. Does it say anything about arrays or sorting in the assignment?
    I suggest you try this for keyboard input; much easier than a buffered reader. There is an example of what you probably want on the first page of the documentation.
     
    Louis Müller
    Greenhorn
    Posts: 14
    IntelliJ IDE Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:
    The bad news is, your assignment appears only to test your knowledge of switch statements.


    I have to think about this but you might be right. Anyways, I found those problems on the webpage of a danish university. Since I only do them for learning java I'm going to stick to my complicated way of solving this. Out of curiosity, stubborness and lack of ideas how to solve it using only the switch statement. I came up with all of this because as output, I have to print out how much money I've earned with each product in increasing order. I couldnt come up with an easier solution. If I'd only have to print them out I think there would be no problem.

    Didn't I give you a Java™ Tutorials link yesterday? Have you read it?


    I opened it and then forgot it between the many tabs i had opened. Sorry for that I will educate myself and then come back.
     
    Louis Müller
    Greenhorn
    Posts: 14
    IntelliJ IDE Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Alright!

    First of all 2 comments concerning the following monolog:
    I) I would've changed the class name "yoyo" but I was worried it would cause me trouble. Be assured that I will choose better names for all of my future classes.
    II) I will also write another version using Scanner. Scanner is actually how I got introduced to Java by a friend but I couldnt figure out how to use it in this situation. I will but that is not what this thread is (or became) about.
    III) Since nobody will check whether I have completed this assignment or not, all I care about is to get the sweet old knowledge out of this. Therefore I wrote a summary of what I did. I'd love if one of you would give it a glimpse to check if I'm about to get wrong information in my brain.

    Summary
    1. I made the class "Product" this class consists of the integer productNumber and the double money. I used a Constructor in which I used the keyword this to make clear which one of the variables is the one of the Object accessing it.

    2. In the Product class implemented is the Comparable Interface. Together with a new (through @Override) compareTo (Product o) method, this enables me to compare 2 Objects of the type Product based on their ID (In my case this is the productNumber). I could verify this by creating 2 Objects of the type Product and use the compareTo method on them. It worked.

    3. In the main method, I created an Array of Product-objects. I asigned the values of productNumber & money to it. I got money through using a Switch statement.

    4. I used Arrays.sort to sort my Array of Objects. the sort method used my own compareTo method to figure out how to sort my objects. Since i told it to use productNumber of the two Objects in comparision it did exactly that. When printing it out, even tho I'm using toString I still get the output I'd usually get if I wouldnt use the toString method. Do you know why?


    Open Questions:

    a) If I would've used an ArrayList instead of an Array of objects, am I right to assume that I would have to use Collections.sort in that case?
    b) What is the purpose of getMoney() method in my Product-class ? Again Am I right to think that I would only need this if I were to sort my Array by he double value?
    c) I'm not entirely sure about this:
    Product is the Object that is subject to the comparision is that right? And o? It is new to me that I don't have to declare "o" before using it. Is it because this is just part of the method and I dont have to understand it ? So just accept it as a fact like the if statement?
    d) Winston proposed
    I will try and do this. Are there anymore advises on how I could make my code more efficient or learn more from this example?

    Here is my Code

     
    Campbell Ritchie
    Marshal
    Posts: 62801
    203
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Louis Müller wrote:. . .  the output I'd usually get if I wouldnt use the toString method. Do you know why?

    The first part looks good
    You get a strange‑looking output because arrays never override toString(). Try System.out.println(Arrays.toString(myArray));

    . . . a) If I would've used an ArrayList instead of an Array of objects, am I right to assume that I would have to use Collections.sort in that case?

    Yes and no. If you use a version of Java ≤ 7, straight yes. In Java8, they introduced this method.

    b) What is the purpose of getMoney() method in my Product-class ? . . .

    It allows other code to find out the price. As we said before, it is probably better to say price.

    c) I'm not entirely sure about this: Product is the Object that is subject to the comparision is that right? And o?

    You need two things to compare; the other thing you are comparing is called o in that bit of code. When you wrote Product there, that was specifying the type of o. The object you are comparing to o is whichever object would be “this” inside that method.

    It is new to me that I don't have to declare "o" before using it. . . .

    But you have declared it. If you declare o as a parameter of the method, that counts as a declaration.

    d) Winston proposed
    4. Why not add a "constructor" to Product that takes a BufferedReader? That way all your 'creation' logic is contained in in the Product class, . . .

    What Winston showed you is actually much cleverer than a constructor; it is a static factory method. I shall let you look it up. Try in Effective Java by Joshua Bloch somewhere in chapter 1.

    And I still think you should rename your class. Yes, it might take some time.
     
    Campbell Ritchie
    Marshal
    Posts: 62801
    203
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Louis Müller wrote:. . .
    Here is my Code

    You don't need n=...; anywhere in that switch, nor do you need the money and re local variables. You can write much neater code if you omit those things. Also find out the difference between double and Double.
     
    Winston Gutkowski
    Bartender
    Posts: 10720
    68
    Eclipse IDE Hibernate Ubuntu
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Louis Müller wrote:Here is my Code


    Blimey. Things certainly have moved on. Kudos on discovering Comparable - you're obviously thinking along the right lines.

    However, "comparability" and "equality" are very closely connected, so if you're adding a compareTo() method, you should probably add equals() as well, because the two should almost always rely on the same fields - usually all of them.

    Indeed, whenever you write a class, you should generally add equals() and hashCode() methods for it before you do anything else.
    And they both have rules that you need to understand before you do. They're not onerous, but the are tricky, and many programmers - even experienced ones - get them wrong.

    Getting back to your compareTo() method: You've only included productNumber in your comparison, probably because you're assuming it will be in a Collection that eliminates duplicates. That's bad thinking.
    In general Objects should be compared on ALL fields that can be different, not just something you assume will be a key.
    Right now, you can create two Products with the same number, but different prices, but they will compare as equal, simply because their numbers are the same.

    Your compareTo() method should be:

    Now, going back to equals(), here's the template for it:
    and those first two checks are important - especially the second one. And they're needed because equals() takes an Object, not a Product.
    The first one simply says, 'if o is the same object as me, we must be equal', and bypasses a lot of unnecessary logic.
    The second one says  'if o is not the same type as me, we cannot be equal', and is absolutely required.
    The rest is hopefully obvious.

    However, now you have a compareTo() method, you can shorten it quite a bit, since it will return 0 when the two objects are "equal", viz:

    Hope I'm not blinding you with too much at once. :-)

    Winston
     
    Campbell Ritchie
    Marshal
    Posts: 62801
    203
    • Likes 2
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I am still dubious that Product in this case has a natural ordering. You can order products by price or by ID, so they don't have one natural ordering. As I said earlier, in that case a Comparator<Product> is probably better.
    You can get away with − for small numbers all with the same sign, but there is a risk of overflow errors if you include negative numbers. You can't use − fof floating‑point values in compareTo(). If you search Rob Spoor's posts about two months ago, he links a talk from Devoxx where they recommend you use this for such comparisons.If there is a possibility of different signs and large magnitudes of ID, try this instead:-
     
    Winston Gutkowski
    Bartender
    Posts: 10720
    68
    Eclipse IDE Hibernate Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:I am still dubious that Product in this case has a natural ordering.

    True, but in the real world "products" usually have an identifying 'name'.

    @Louis - Does yours?

    Winston
     
    Winston Gutkowski
    Bartender
    Posts: 10720
    68
    Eclipse IDE Hibernate Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Oops. BIG mistake in my compareTo() method:

    this.money - that.money

    won't work, because money is a double.

    Will post the correct solution later in a couple of hours. Have to go now.

    Winston
     
    Campbell Ritchie
    Marshal
    Posts: 62801
    203
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Winston Gutkowski wrote:. . . in the real world "products" usually have an identifying 'name'.

    @Louis - Does yours?

    Winston

    Not yet he hasn't.

    A natural ordering usually means you always sort the same way; I can think of at least three ways to sort products: by ID, by price, and by name.
    In which case java.lang.String has two likely orderings, so‑called ASCIIbetical and dictionary order, in which case maybe String shouldn't have implemented Comparable.
     
    Winston Gutkowski
    Bartender
    Posts: 10720
    68
    Eclipse IDE Hibernate Ubuntu
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Winston Gutkowski wrote:Will post the correct solution later in a couple of hours.

    This is probably easiest to follow:
    the last five lines of which can be reduced to:
    return diff > 0.0d ? 1 : diff < 0.0d ? -1 : 0;
    but wasn't sure if you've come across the ternary (?:)  operator yet.

    Winston
     
    Bartender
    Posts: 20307
    110
    Android Eclipse IDE Linux
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:
    By the way: Java® only supports 1D arrays; what appear to be 2D arrays are really arrays of arrays.



    And 1D arrays are called vectors by mathemeticians. But Java® defined Vector as a resizable linear collection with built-in synchronization. Not one of their best decisions, alas.
     
    Winston Gutkowski
    Bartender
    Posts: 10720
    68
    Eclipse IDE Hibernate Ubuntu
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:...a talk from Devoxx where they recommend you use...

    Yes.

    @Louis - Listen to Campbell. His solution is way better than mine (even after I corrected it :-) ).

    Winston
     
    Louis Müller
    Greenhorn
    Posts: 14
    IntelliJ IDE Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    First of all: the improved version of my code so far. I hope this will make it easier to talk about it.



     
    Louis Müller
    Greenhorn
    Posts: 14
    IntelliJ IDE Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Alright. You've been giving me a big field to graze on if I may : D

    Right now, you can create two Products with the same number, but different prices, but they will compare as equal, simply because their numbers are the same.


    This is correct and comprehensible. But what would that mean for my (old) code? It will return a 0 to the sort method and next? Also I took the task for something like the final calculation after a year of selling product 1,2,3,4,5 therefore I assumed the same product number not to occur twice. But I submitted it at the universitys-page and got an error in both test cases even tho the given examples worked fine in IntelliJ. So probably, I was mistaken.

    and those first two checks are important - especially the second one. And they're needed because equals() takes an Object, not a Product. The first one simply says, 'if o is the same object as me, we must be equal', and bypasses a lot of unnecessary logic. The second one says 'if o is not the same type as me, we cannot be equal', and is absolutely required. The rest is hopefully obvious.


    So the first test is just to safe my programm some work is that correct? Just to make it work faster in the case of two identical Objects? I'm a bit confused about the difference between object and Product. As far as I know now, the equals method checks if two objects have the same "memory space"? In other words whether I've used only one keyword "new" to invoke both of them. Is that correct?
    I shamefully admit that the rest, also, is not obvious.

    First we checked whether or not the objects are equal. Then whether they are not of the same type. If the first of those checks is false and the second true (doesnt return false) then we proceed to assigning product that to o? Where is product that coming from and why is it product o? Then we're returning the value of productNumber this & that which are the same as we've just figured out. Same with money. For me this doesnt make sense. If the product number is the same shouldnt we add this.money += that.money in this manner? because in this case we sold more of product number x !

    @Louis - Does yours?  



    Yes I do think they have an identifying name!
    product 1, $2.98;
    product 2, $4.50;
    product 3, $9.98;
    product 4, $4.49;
    product 5, $6.87.

    they are called product 1,2,3,4,5.




    The compareTo method made way more sense to me. But then you corrected it and now it is of return type boolean. I really thought it would be int.


    the last five lines of which can be reduced to:
    return diff > 0.0d ? 1 : diff < 0.0d ? -1 : 0;  



    Yesssss I know this one : D

    Well yeah I might still need some time with this problem !


     
    Louis Müller
    Greenhorn
    Posts: 14
    IntelliJ IDE Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I will read a chapter in "think Java" and maybe "programming java" about this and then come back. No need for you to explain it all to me. After all, this is not a college. Safe yourself some time, I'll be back.
     
    Winston Gutkowski
    Bartender
    Posts: 10720
    68
    Eclipse IDE Hibernate Ubuntu
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Louis Müller wrote:The compareTo method made way more sense to me. But then you corrected it and now it is of return type boolean. I really thought it would be int.

    And you're absolutely right, it is. The signature should have been:

    @Override
    public int compareTo(Product p) { ...


    I was copying and pasting too quickly and forgot to change the return type.
    My sincere apologies.

    More to follow, but I wanted to get that out of the way first...

    Winston
     
    Winston Gutkowski
    Bartender
    Posts: 10720
    68
    Eclipse IDE Hibernate Ubuntu
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Louis Müller wrote:Alright. You've been giving me a big field to graze on if I may : D

    Hope you're enjoying the ride. :-)

    Louis Müller wrote:So the first test is just to make it work faster in the case of two identical Objects is that correct?

    Correct.

    Louis Müller wrote:I'm a bit confused about the difference between object and Product.

    Object with a capital O.
    equals() is inherited from Object, which has no notion of Products, because your class wasn't written when it was created. Therefore the only thing equals() knows about is other Objects. Which is why its signature is:
    @Override
    public boolean equals(Object o) { ...

    (and equals() does return a boolean :-) )

    Louis Müller wrote:As far as I know now, the equals method checks if two objects have the same "memory space"?

    That's what it does if you don't override it, but it's not what the method is there for.
    From the docs for Object.equals():
    'Indicates whether some other object is "equal to" this one.'
    And the notion of what "equals" means is usually different for each class.

    I shamefully admit that the rest, also, is not obvious.
    OK. Maybe some comments will help:
    And here's the docs for ClassCastException

    Louis Müller wrote:For me this doesnt make sense. If the product number is the same shouldnt we add this.money += that.money in this manner? because in this case we sold more of product number x !

    I don't think you quite understand the idea of an 'order'.
    Basically, what compareTo() (or, as Campbell suggested, a Comparator) does is to provide a way of deciding whether one object is "greater than", "less than", or "equal to" another object of the same type. And you do it so that you can sort them in a predictable way.

    And usually - not always, but most of the time - it will be closely related to equals(), and involve comparing the same fields.
    This is called "making comparison consistent with equals()", and is usually a good thing.
    And since compareTo() must return 0 if the two objects are "equal", it makes sense for equals() to use it if it can.

    Louis Müller wrote:Yes I do think they have an identifying name!
    product 1...

    Hmmm. Doesn't mean much does it?
    Wouldn't "Baked Beans" (or whatever) be better? Certainly easier for us puny humans.

    Louis Müller wrote:The compareTo method made way more sense to me. But then you corrected it...

    Yes, and I really apologise for that. Hopefully I've cleared things up now.

    Good luck with your reading. :-)

    Winston
     
    Winston Gutkowski
    Bartender
    Posts: 10720
    68
    Eclipse IDE Hibernate Ubuntu
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Agh! I still got it wrong. Sheesh.
    Boy, I'm out of practice .... and thanks to Campbell for pointing it out to me.

    equals() returns a boolean, so it should be (with comments as before):

    However, if you also have a compareTo() method, eg:
    you can use it in your equals() method.
    (this time without the comments):and the reason for doing it that way is that then both methods use the same "comparison" code, and therefore must be consistent.

    Apologies for all the mistakes. :-)

    Winston
     
    Louis Müller
    Greenhorn
    Posts: 14
    IntelliJ IDE Java
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator


    I wrote my current problem in the comments. The reading helped a lot but I think apart from this I'm slowly seeing through this.
     
    Winston Gutkowski
    Bartender
    Posts: 10720
    68
    Eclipse IDE Hibernate Ubuntu
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Louis Müller wrote:why am I using compare? I thought this is a method of Comparator.


    It is. However Comparator.compare() takes two objects, because Comparators are typed, and types are usually classes.

    But Double has a static compare() method that takes two doubles (note: not Double) so that you can compare two primitive values in the same way as Comparator compares objects.
    And all the Number classes have similar methods for their own primitive type.

    I suspect they used that name to indicate that the method is "Comparator-like".

    Hope it helps. Also: check out the 'docs' link. It might help.

    And BTW: You're asking all the right questions. Well done (gave you a +1).
    A lot of this stuff IS confusing when you first run into it.

    Winston
     
    Campbell Ritchie
    Marshal
    Posts: 62801
    203
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Winston Gutkowski wrote:. . . And all the Number classes have similar methods for their own primitive type.

    I suspect they used that name to indicate that the method is "Comparator-like". . . .

    Those methods are designed to get around the problem that using subtraction can cause an overflow error, not to mention that the value NaN (only seen with floating‑point numbers) has some weird behaviour if you use the != == < <= > and >= operators on it. Using those compare() methods gets around those problems.
    If you go through the Comparator documentation you will find some methods with strange‑sounding names starting “comparing”. You can sort your List<Product> with a Comparator like this:-The procedure for an array would be quite similar.
    You will have to read the documentation, and also find the Java™ Tutorials section about λs.
    You start off requiring a Comparator<Product>; because the compiler “knows” that you have a List<Product>, it will “assume” that any Comparator provided will take the right type of arguments. What you have on the right is a λ instructing the JVM to take any Product (p) supplied and get its idNumber; the same applies later on where you are getting the price instead. The second line is only executed if the first line produces a result 0. The documentation for Comparator#thenComparing() says,

    If this Comparator considers two elements equal, i.e. compare(a, b) == 0, other is used to determine the order.

    It also says that thenComparingDouble works similarly.
     
    Louis Müller
    Greenhorn
    Posts: 14
    IntelliJ IDE Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Alright. I finally got all them sweet points from the assignment. They are only virtual, but the satisfaction is real.

    However there are still a few things left for me to understand. (I added the whole code down below even though I assume you wont be keen on reading it. It wont be necessary to answer my questions.)


    1.
    Since I had to find a way to deal with the case of the same product number occuring twice in the input. I included this condition in my ReadInputGetPrice class


    I'm not happy having all that code in that class. I'd much prefer to create a separate method getIndex to include the for loop. But I couldnt figure out how to access the namesAndPrices Arraylist from outside of the method. Is it because Im using it in the following for loop? I thought it would be defined as public by default and therefore be accessible.

    2.

    Winston Gutkowski wrote:and the reason for doing it that way is that then both methods use the same "comparison" code, and therefore must be consistent.  


    In contrary to using a equals method based on the == operator instead of the compare(primitive type) method ?

    3.
    I didnt need the equals method at all. This is not to say that you gave bad advice. I assume this method usually is extremely helpful, only in this assignment for noobs, it wasn't needed. We agreed that one would use the equals method to safe the program some unnecessary work. But I feel like in this assignment, due to the way the problem is articulated and the kind of problem we're dealing with I think there cannot be the same object twice. Also I dont think there can be an object other than the ProductsAndSellingPrices (former Product) object.

    4.

    Campbell Ritchie wrote:I am still dubious that Product in this case has a natural ordering. You can order products by price or by ID, so they don't have one natural ordering.


    Winston Gutkowski wrote:I don't think you quite understand the idea of an 'order'.
    Basically, what compareTo() (or, as Campbell suggested, a Comparator) does is to provide a way of deciding whether one object is "greater than", "less than", or "equal to" another object of the same type. And you do it so that you can sort them in a predictable way.

    And usually - not always, but most of the time - it will be closely related to equals(), and involve comparing the same fields.
    This is called "making comparison consistent with equals()", and is usually a good thing.



    This keeps bothering me because I think you are wrong in this case. Considering my imense lack of knowledge, this is a bold assumption and I'm not about to insist on that But, after researching on natural ordering I came to the conclusion that my products do have a one. The are ordered by the productNumber. Thats what I wanted to achieve the whole time. Since I dont want to order my list based on any other property than on the product number I think comparable is the best option. To back my opinion let me quote Stackoverflow:

    "I would say that an object should implement Comparable if that is the clear natural way to sort the class, and anyone would need to sort the class would generally want to do it that way.
    If, however, the sorting was an unusual use of the class, or the sorting only makes sense for a specific use case, then a Comparator is a better option."




    Campbell Ritchie wrote:λ


    I will look into this (and your last post in general) tomorow because I'm too worn out right now to grasp yet another concept. I tried to understand λ already when trying to figure out streams but failed (with both). I will try it tomorrow but I might skip it if I'll face the same confusion as last time. In this case I will just wait till I feel comfortable with all those classes and objects before tackling the lambdas again. (I prefer to primarily associate them with wavelenght for a while too)


    Finally:

    Hope you're enjoying the ride. :-)


    Hell Yeah I did. I had the best time these days learning all of that with your help. This forum is great, you two are great. No need to apologise for any mistakes, as long as you correct them there is even more for me to learn !!!


     
    Louis Müller
    Greenhorn
    Posts: 14
    IntelliJ IDE Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Now, here comes the code..



     
    All of the world's problems can be solved in a garden - Geoff Lawton. Tiny ad:
    RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database
    https://coderanch.com/t/704633/RavenDB-Open-Source-NoSQL-Database
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!