• 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
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

Passing objects by value instead of by reference (Java 16.0.1)

 
Ranch Hand
Posts: 72
2
Eclipse IDE MySQL Database Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,

While practicing with putting objects in objects I notices objects are passes by reference and not by value (jdk 16.0.1).
Is it possible to pass objects by value?

Thanks,
~d

 
Marshal
Posts: 73984
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Where did you find that? It is news to me; Java® has always passed everything by value full stop. Look at this old thread, including the two links I posted. They include links to this JLS (=Java® Language Specification) section, which tells you.

When the method or constructor is invoked (§15.12), the values of the actual argument expressions initialize newly created parameter variables, each of the declared type, before execution of the body of the method or constructor. The Identifier that appears in the FormalParameter may be used as a simple name in the body of the method or constructor to refer to the formal parameter.

Newly created variables represent pass by value, and that hasn't changed in Java16.
 
Marshal
Posts: 16591
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

David Cone wrote:Hello,
While practicing with putting objects in objects I notices objects are passes by reference and not by value (jdk 16.0.1).
Is it possible to pass objects by value?


Please show us your code that made you come to that (erroneous) conclusion and we'll try to help clarify what's actually happening.

As Campbell said, parameters are always passed by value in Java. It's just that if you pass a reference to a mutable object, anything that is done through that reference in the called method will potentially affect the state of the object and thus will be observable from outside of the method.

The above code demonstrates the difference. The assignment on line 12 will only affect the numbers parameter (essentially a local variable). It doesn't affect the nums variable in foo(). The change on line 10, however, will be seen in foo().
 
David Cone
Ranch Hand
Posts: 72
2
Eclipse IDE MySQL Database Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Obj1.java:


Obj2.java


Main.java


Output on my pc in IntelliJ IDEA Comm. E. 2021.1.2 x64:

"D:\Program Files\Java\jdk-16.0.1\bin\java.exe" "-javaagent:D:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2\IntelliJ IDEA Community Edition 2021.1.2\lib\idea_rt.jar=57951:D:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2\IntelliJ IDEA Community Edition 2021.1.2\bin" -Dfile.encoding=UTF-8 -classpath D:\Users\David\IdeaProjects\ObjectInObjectDemo\out\production\ObjectInObjectDemo com.user404.Main
          Object 1's integer is 1
Object 2's (object 1 integer) is 1
          Object 3's integer is 1
          Object 1's integer is 16
Object 2's (object 1 integer) is 16
          Object 3's integer is 16
          Object 1's integer is 8
Object 2's (object 1 integer) is 8
          Object 3's integer is 8
          Object 1's integer is 32
Object 2's (object 1 integer) is 32
          Object 3's integer is 32

Process finished with exit code 0


 
Junilu Lacar
Marshal
Posts: 16591
277
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
That's a lot of code to read, analyze and reason about. Can you describe a specific flow in that code that you think shows that Java is passing parameters by reference rather than by value. Please indicate which line numbers you're referring to when you describe the flow. THanks.
 
Junilu Lacar
Marshal
Posts: 16591
277
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 can tell you that after scanning your code, there is nothing in it that is inconsistent with the fact that Java passes *all* parameters by value. I think the reason you think it's by reference is because your objects are mutable. The parameters *are* being passed by value, except in your program, the values are object references. Since the object references are always pointed to the original object, any state changes that happen to the object through those passed in references will affect the original object and be visible outside of where those changes were made. To avoid this kind of "leakage", you either have to pass in immutable copies from the calling code or make copies of the object passed in to the called code.
 
Bartender
Posts: 4631
182
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
AFAIK: it is passing by value, but that value is a reference for non-primitives.
 
David Cone
Ranch Hand
Posts: 72
2
Eclipse IDE MySQL Database Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
OK, so I used the wrong language.  MY BAD!!! I apologize!!! (gee whiz)  How do I keep it from being muteable (or whetever)?
 
Sheriff
Posts: 26771
82
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

David Cone wrote:How do I keep it from being muteable (or whetever)?



"Mutable" means "Can be changed". Your classes there have setter methods which allow an object of that class to be changed.

And "changed" means specifically that the object's state can be changed. An object's "state" is (basically) its instance variables. So an immutable object may have instance variables, but they would only be initialized by the constructor and not ever changed later by external accessors. It's actually more complicated than that (Rule 2 of LTTUAE) but that's the beginner's version.
 
Junilu Lacar
Marshal
Posts: 16591
277
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

David Cone wrote:How do I keep it from being muteable (or whetever)?


There are a few ways to do that:
1. Pass in a copy of the object
2. Make a copy of the object that your receive and operate on the copy instead.
3. Wrap the object with a decorator that doesn't allow modifications to be made. For examples, see the java.util.Collections.unmodifiableXXXX() methods.
4. Make all your object fields final.

There may be other ways, too, which I will leave for others to suggest.
 
Campbell Ritchie
Marshal
Posts: 73984
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

David Cone wrote:. . . MY BAD!!! . . .

Don't worry about it; you haven't done anything wrong.

How do I keep it from being muteable (or whetever)?

You don't. You can't. If somebody has designed a mutable class, it remains mutable for ever. You would have to follow the usual conventions for making immutable objects otherwise. If you go through resources like Joshua Bloch's Effective Java, you will find out that immutable objects have all sorts of advantages.
 
Junilu Lacar
Marshal
Posts: 16591
277
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
There are many reasons to favor immutable objects, although it's not always possible/practical to write programs that use only immutable objects. (Functional programmers might have a big problem with that statement though)

1. You can write programs that are more functional (see functional programming and immutability)
2. Immutable objects are inherently thread-safe
3. Immutable objects are immune from surprising side-effects when passed as parameters to other functions/methods.
4. It's easier to reason about code that uses only immutable objects. Stateful objects are more complex/complicated to reason about.
 
David Cone
Ranch Hand
Posts: 72
2
Eclipse IDE MySQL Database Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Now that I'm a bit calmer,  let me try this again.

I updated my bio information on this site, if you want to know a bit more about me.  Maybe it will help you understand me a bit more. I also updated my signature.

I'm teaching myself programming.... I get I have a lousy teacher.  I'm also taking a Java course on Udemy.com (based on a recommendation by someone on this site)... we haven't even learned System.out.print yet (only println), but I'm choosing to go through the entire course anyways.  Part of what helps me trudge through the course is working on some of my own interests (which is what I'm doing now.)  I do plan on taking Java programming in college in the fall semester starting in August.  At that point any school related question will only be asked of people at the college. I have zero interest in having others do my homework.

The way I learn stuff best is to try and solve problems I think of that interest me.  I'm trying to learn about objects inside other objects.  I like to learn by example...  When I don't understand something about a solution I like to ask questions.  That's what seems to work best for me.  I fully understand that this approach may not work well for others.  I never claimed to be like anyone else.

I started learning Java (from a book) and from online examples back on 5/21/2021.  So today is day 26.  When you reply to  me, please keep this in mind.  I wonder how much of what people have told me today would have made sense to them on their day 26.

I started reading up on formal programming / immutability...  It seems useful, but it's all a bit above my head at this time.

I would very much appreciate it if someone could show me how to put the contents of an object into another object in such a way that if I update the first object, the 2nd object is not effected.

If you don't want to do that, I'm OK with it.... give me crickets.  If, however it adds to your life by showing me how this is done, that would be AWESOME and I would be grateful.  

Thank you for your time and consideration.

May you have a peaceful and rewarding day,
~d

 
David Cone
Ranch Hand
Posts: 72
2
Eclipse IDE MySQL Database Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
error in response: Cannot cast type mountain into type molehill.
 
Paul Clapham
Sheriff
Posts: 26771
82
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

David Cone wrote:I'm trying to learn about objects inside other objects.


First thing to know: Objects don't contain other objects. The actual situation is that an object has a set of instance variables; each of those is either a primitive type, which contains a primitive value such as 22 or false, or it's a reference type, which contains either the null reference or a reference to some other object. That other object isn't "inside" the first object, and many other objects can also contain a reference to it. So you can think of that as objects containing pointers to other objects. They are called references in Java but basically a reference allows an object to point to other objects. If you're into drawing pictures then you would draw an arrow from an object to another object which it refers to.

I would very much appreciate it if someone could show me how to put the contents of an object into another object in such a way that if I update the first object, the 2nd object is not effected.


So now I'm unclear about what you're asking. When you say the "contents" of an object were you thinking of the instance variables of that object? Perhaps you could draw a picture of the object graph you have in mind and then examine what that question means?
 
David Cone
Ranch Hand
Posts: 72
2
Eclipse IDE MySQL Database Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Paul,  (on a side note, I'm less cry-baby now)

My artistic aptitude is way low.  I don't even do stick figures well.  Someday I'll post some of my "artwork" for everyone's amusement.

Thank you ever so much for your explanation.  Let me try a few things using my new understanding and perhaps it is now a non-issue.

Thank you for being awesome,
~d


 
Campbell Ritchie
Marshal
Posts: 73984
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
To repeat what I said last night (sort of):-
Objects are mutable or immutable. It is possible to restrict mutability by not making methods public, or by requiring methods to validate an argument before allowing a change of object state, but within those constraints, “once a mutable object, always a mutable object.” If an object has a reference to another object, that second object can change its state if it is mutable and accessible from other code. If you pass a mutable object to a method, that method will “assume” it is permitted to change the state of that object. If you want to control mutability, make sure you are the only person with a reference to a particular object. Whenever a mutable object comes into your object, via the constructor, or a setXXX() method, or similar, take a copy of that object. Copy first, validate afterwards. Whenever you let a mutable object out of your object. maybe via a getXXX() method, make sure it is a copy of the object you send. If you do that, you will be the only person with a reference to that object, and you can restrict any changes to what you want yourself. There is a chapter in Joshua Bloch's Effective Java about taking defensive copies, which is what the procedure above is called.
 
David Cone
Ranch Hand
Posts: 72
2
Eclipse IDE MySQL Database Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@Ritchie  I've read that a couple times now. It's 3:48am and I need sleep.  I can't promise that tomorrow I'll try again, but I will someday soon.

@Paul I'm guess I got this figured out to a point that I'm satisfied... Here's my more realistic test code.

Address.java:


User.Java:


Main.java:


Output:

Dave Cone
1 Hard Dr
Santa Ana, CA 92707
And now for someone... completely different.

______

I'm Real
1 Hard Dr
Santa Ana, CA 92707
unreal!


===============


Dave Cone
1 Hard Dr
Santa Ana, CA 92707
And now for someone... completely different.

______

I'm Real
1 USB St
Riverside, CA 92505
unreal!

Process finished with exit code 0


Is that reasonable code for day 27 of learning Java?
 
Junilu Lacar
Marshal
Posts: 16591
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

David Cone wrote:error in response: Cannot cast type mountain into type molehill.


I believe you meant the other way around: don't try to cast a Molehill into a Mountain

Since you're posting in Beginning Java, everyone understands you're a beginner. What we don't know (or didn't before you let it all hang out) is just how much of a beginner you are. It's okay. It's okay to say "Sorry, I haven't learned about that stuff yet." Don't feel bad if people try to tell you more than you're ready to take on. Just say so. Nicely. It's no knock on you if don't understand things yet.. you will, hopefully, eventually, get it.

When I first started posting here and people pointed out my mistakes or things I misunderstood, I felt kind of embarrassed, even though there was nobody around. It's a natural reaction, I think, but there's really no need to feel embarrassed, much less angry when people try to explain things that are still over your head. Again, just say something like "Sorry, but I don't know about that stuff yet. Let me look into it though."

Happy learning!
 
lowercase baba
Posts: 13002
66
Chrome Java Linux
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you have a line like:



You have created a User object somewhere off in memory.  You also create a User object reference variable called "me" that is then given a value that lets the JVM find that actual object off in memory.


Think of it like telling a home builder "Go build me a house somewhere."  The builder does that, and says "OK, here are the GPS coordinates of your house i built".  You write it down on a piece of paper labeled "MyHouse".

that "MyHouse" piece of paper does not hold the actual house...it just tells someone how to find the house.

I can now make copies of that piece of paper, and hand that out to as many people as I want.  "here is my house"..."here is my house", etc.  You're not giving them the actual house, you're just telling them how to get there.  If someone goes there and paints the living room blue, then that living room is blue for anyone who subsequently goes there and looks.  If someone later paints it yellow, now it's yellow for everyone from that point on.

If I don't want anyone to be able to change the house, I can still give them the address, but not let them in to change it (maybe by putting a lock on the door).

Your variable "me" contains a house/object address.  When you pass "me" into a method, you're making a copy of the address, and handing it to the method.  Now that the method knows how to get to your object, if your object allows things to change it, it can be changed by the method.

 
Campbell Ritchie
Marshal
Posts: 73984
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

David Cone wrote:. . . It's 3:48am and I need sleep. . . .

Unless you are a lot more of a night owl than I am, don't work that late. And make sure not to overwork; it is simply counter‑productive. You need every bit of brain working to learn programming.
 
David Cone
Ranch Hand
Posts: 72
2
Eclipse IDE MySQL Database Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@Ritchie...  It's not as much "nightowl" as it is "Insomnia".  I did get a couple of hours sleep before I woke up again at ~11:30.pm.  I'm a huge fan of sleep.  I fully believe in it and seek a rested state every day.

@Fred I totally understand your house example, thank you good sir.

@anyone - I still don't get what an immutable program looks like.  Can anyone give me a side by side... a short program or snippet in mutable form and then the same thing in immutable form.  That would help me greatly.  If it makes it easier, what would an immutable version of a program I have already written looks like.  If you have homework fear, one of your own.  To quote my sister, this is all great in Theory, but I don't live anywhere near, Theory.

@Junitu. - No, I said it the way I meant it.  I felt like I was bringing mole-hill problems and getting mountain answers which don't cast well back into mole-hill.  Not angry, overwhelmed.  A dadism:  How do  you eat an elephant sandwich?  One bite at a time.  I keep trying to take a bite out of learning Java and people keep handing me back new sandwiches.  So instead of feeling like I'm making progress, I feel like I'm falling further behind.  In this case, I was trying to learn about objects stored in other objects.  Responses: "you need to understand immutability and formal programming"...  something you can write an entire book about...  something I wasn't aware that I wasn't aware of it.  Now it's in queue to learn.  A queue that feels like it's about to overflow.  And I get that people are sincere in there efforts to help and I 'm sure that in some cases bring up what they do will keep me from learning a wrong way and having to unlearn it, so I am appreciative. but that doesn't make it any easier for my head to wrap around the micro-topic that I'm working on at a given moment.  I do not choose to proclaim ADD or ADHD or any of those labels over myself.  However, I will admit sometimes it's hard to focus on one specific subject, so that adds to the dilemma as well.

Have an AWESOME day,
~d
 
Campbell Ritchie
Marshal
Posts: 73984
332
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It's not an immutable program but an immutable object. Lots of classes produce immutable objects, e.g. String, Integer, BigDecimal (with reservations), LocalDate. If you go through the API for String and look for methods with void instead of a return type. I don't think there are any. There is no way you can change the state of a String object (not without doing something very naughty anyway). Once its state has been set up, it retains the same state for the whole of its lifetime. There is a section in the Java™ Tutorials about immutable objects.
 
Junilu Lacar
Marshal
Posts: 16591
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
An immutable object is one whose state cannot be changed once it is created. That's usually accomplished by declaring the instance variables as final, which prevent the variable from being changed once it's set.

A User must be created with a non-null name value, otherwise a NullPointerException will be thrown by Object.requireNonNull(). Once a User object has been created, there's no way to change its name. You have to create a different User object with another name value. Since the User class has only instance variable (i.e. its state) whose value is immutable, we say that User is immutable.

#1 - the name field is declared as final; this makes it writable one and only one time and its value must be set during object construction
#2 - the value for name needs to be passed in to the constructor
#3 - validation: the name value cannot be null otherwise a NullPointerException will be thrown
#4 - the name field is set to the value passed in - any attempts to assign a value to name after this will not be allowed and will cause a compile-time error.
 
Junilu Lacar
Marshal
Posts: 16591
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Now, when we say "make a defensive copy" of an object, that means that instead of keeping the reference received as a parameter, you immediately make a copy of the object that is referenced and use the copy instead of the reference that was passed in.

Here's an article that explains the concept in pretty good detail: https://javacreed.com/what-is-defensive-copying
 
Junilu Lacar
Marshal
Posts: 16591
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

David Cone wrote:In this case, I was trying to learn about objects stored in other objects.  Responses: "you need to understand immutability and formal programming"


Well, no, that's not exactly true, at least that's not how your question was framed.

Your question was specifically about pass by reference vs. pass by value semantics. The short answer to your question quite simply was "No, parameters are always passed by value in Java."

However, just saying that isn't enough to help you understand why you were seeing what you were seeing that made you think that the parameter was being passed by reference even though it isn't. So any explanation that would help you understand better will need to get into the concepts of mutable vs immutable objects. That's why you got all the way from "pass by reference vs pass by value" to "you need to understand mutability." You thought that you got a mountain when all you were asking for was a mole-hill but really what you got was "well to understand what's going on with that mole-hill, you have to understand what's going on with the anthill next to it."
 
David Cone
Ranch Hand
Posts: 72
2
Eclipse IDE MySQL Database Windows
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@Junilu - fair enough.

@all - Is this up to standards?


Address.java:


User.java


Main.java:


thank you for your time,
~d




 
David Cone
Ranch Hand
Posts: 72
2
Eclipse IDE MySQL Database Windows
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Version 1.2

Main.java;
 
Junilu Lacar
Marshal
Posts: 16591
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Campbell pointed out that you can actually do this:

The reason I showed you the longer way before was so I could explain what has happening in a more step-by-step way.

You can do that for all the fields in your object.
 
David Cone
Ranch Hand
Posts: 72
2
Eclipse IDE MySQL Database Windows
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@Campbell - brilliant as always!  Thank you good sir.  BTW, I noticed I got your advise indirectly.  If I offended you, I deeply apologize!   Oh, I did get some more sleep this afternoon.  Thank you for your concern.

@all -  With a cool post on stackoverflow.com (referenced in code comments) and Campbell's streamline, I got a new version of this program that uses ArrayList to print out the users.  I'm happy to say I got it working! (woot!)  Before I work on 2.0 which will be getting the list from a file,  I feel like there is probably some more streamlining to be done.  Which is to say I know your brilliant minds can do it more efficiently.... perhaps there's a way to create a new user and add them to UserSet in one shot.  For now I'm off to play some Bloons TD 6, and then I'll dive back into Udemy.com's program.  I'm happy to say I found the bug in the  teachers code (which he points oout in the next video) before watching the next video that told me about it.  I also found a streamline that he didn't mention.  I feel like I've made good progress today.   Oh yeah, before I go... the new code.

Address.java:


User.java:


Main.java:


Have a way cool evening/night,
~d
 
Campbell Ritchie
Marshal
Posts: 73984
332
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Junilu Lacar wrote:Campbell pointed out that you can actually do this:
. . . .

The Objects class was introduced in 2009, in Java7. It has all sorts of useful methods in and I think I should have been introduced in Java1.0! Just my opinion. In the meantime, many people wrote their own classes to do the same sort of thing.
Don't call a List xxxSet. That would mislead your readers into thinking it is a set, and sets behave differently from lists. Note: some people call lists sequences. I think users would be a better name for it.
 
Campbell Ritchie
Marshal
Posts: 73984
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

David Cone wrote:. . . Thank you . . .

That's a pleasure

If I offended you . . .

You didn't offend me, but it never does any harm to consider whether an apology would be appropriate.

. . . create a new user and add them to UserSet in one shot. . .

Something like?
 
Junilu Lacar
Marshal
Posts: 16591
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Don't call a List xxxSet. That would mislead your readers into thinking it is a set, and sets behave differently from lists. Note: some people call lists sequences. I think users would be a better name for it.


This is the code Campbell is referring to:

A couple of things you'll want to note to improve your coding style:

1. Prefer names that express intent, not implementation. The name UserSet reveals or "leaks" an implementation detail. Moreover, the name actually lies to—or misleads at best—the reader because the actual object is a List, not a Set.

2. Prefer to declare abstractions, not concretions. An ArrayList is a concrete implementation of the List interface, which is an abstraction because it only describes behavior, not implementation. That is:

The right-hand side of that declaration uses what's called the "diamond operator" where you just let the compiler infer the type that goes inside the angle brackets based on the declared type on the left side of the assignment. It makes your code less verbose and avoids typing-related errors.

3. Same thing goes with your parameters. Instead of declaring a method as void foo(ArrayList<ElementType> stuff), prefer void foo(List<ElementType> stuff). Of course, per #1, you should use better names than "foo" and "stuff"
 
David Cone
Ranch Hand
Posts: 72
2
Eclipse IDE MySQL Database Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Something like?



I didn't look this up, but it's time to get more sleep (and I'm not sure what search terms to use).  Can I do something like ?

Thanks,
~d
 
Campbell Ritchie
Marshal
Posts: 73984
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes.
 
Junilu Lacar
Marshal
Posts: 16591
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

David Cone wrote:Can I do something like ?


Given the types you've declared, no, you can't do that. The value of an assignment expression is the value on the right hand side of the = operator.

That is, the expression name = new User(...) evaluates to a reference to the User instance that was created by new User(...)

Since name is a String, trying to assign a reference to a User instance to it is illegal.

The fact that an assignment expression evaluates to the value being assigned is demonstrated in this code:

The expression on line 3 is evaluated as though you wrote this:

That is, k = 5 evaluates to 5, which is then assigned to j. The expression j = 5 itself evaluates to 5 again, which is in turn assigned to i.
 
Campbell Ritchie
Marshal
Posts: 73984
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What I meant was that you can create a List<User> and add a User reference to it directly; sorry, but I hadn't noticed that what you wrote was slightly different from what I wrote.
 
David Cone
Ranch Hand
Posts: 72
2
Eclipse IDE MySQL Database Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So I'd loose a reference ID (in this case, the variable name) by doing it in one step.....  and if I add a reference ID to the class, I have no way to ensure it's not duplicated (well I guess it's not impossible, just a bit over my head at the moment...  I was reading up on this at stackoverflow.com and I guess a new class could be made that extends ArrayList, override the .add method to include duplicate checking on the first property and if no duplicate is found, do a "super.add"...  That's all off the top of my head from what I read last night,  Let me see if I can find the reference...  brb.... [time passes] ... Solution Entry by G H...  I'm pleased to say I've read enough about Java that I understand what he's saying....  just not enough to program it.) I think I'll be satasfied with the code as it is for now.  Later I'll add the ability to read the data from a file.  For now I'm having fun doing code exercises on Udemy.com.  I had fun doing the "Barking Dog" exercise with a single if statement.  If we were allowed to do it using the ternary operator (which we haven't learned yet) the solution could be done in a single statement:   Off to code... Have a great evening!  ~d
 
Paul Clapham
Sheriff
Posts: 26771
82
Eclipse IDE Firefox Browser MySQL Database
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

David Cone wrote:I was reading up on this at stackoverflow.com and I guess a new class could be made that extends ArrayList, override the .add method to include duplicate checking on the first property and if no duplicate is found, do a "super.add"...



It sounds like you want a List, only you don't want to permit duplicate entries. "Don't permit duplicates" normally suggests that you'd choose a Set and not a List. You'd consider a List if the ordering of the entries is significant.

So is the ordering of the elements significant? Or are you just using a List because that's a familiar thing? If you need a Set (no duplicates) but you later need the entries in the order in which you add them, then you'd use a LinkedHashSet. That way you don't need to check for duplicates, just add the entries to the LinkedHashSet and when you go to get them out of the Set, they will be in the order in which they were inserted.

Edit: I just looked at the Stack Overflow post you referred to and noticed that it was over 10 years old. It's quite possible that LinkedHashSet was too new at that time (released in Java 1.4 in 2002 though) for them to mention it.
 
Campbell Ritchie
Marshal
Posts: 73984
332
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

David Cone wrote:So I'd loose a reference ID (in this case, the variable name) by doing it in one step.....  and if I add a reference ID to the class

You mean, “assign the User object to a reference,” or similar?

I have no way to ensure it's not duplicated . . .

Does the above code help?

at stackoverflow.com and I guess a new class could be made that extends ArrayList, override the .add method to include duplicate checking on the first property and if no duplicate is found, do a "super.add"...

No, that is incorrect; the specification for the List interface says that add() either does nothing at all, or it appends the new element. The corresponding link for ArrayList says that add() appends the offered element full stop. No checking for duplicates or anything like that. That means such a class ISN'T AN array list, and it also ISN'T A list, because lists implicitly always allow duplicate elements. That is virtually part of the definition of a list. If you really want something like that, look for a LinkedHashSet, though maybe learning all the classes in the collections framework is beyond the call of duty for four weeks' experience. Or you can follow their suggestion for a sorted set using the insertion index to sort by. What they forgot is that a tree set only adds in logn time complexity if the input is unsorted; completely sorted input like that will cause it to degenerate to a linked list and its performance will be unnecessarily slow. Also such a set has great difficulty checking that its entries are unique if the insertion index is ignored. Hash sets don't play at all well with mutable objects; if the hash code changes, the object sought will become impossible to find. I don't know whether that applies to a linked hash set.
I see several people on that SO thread said such a class isn't a list, which I think is correct.

. . . If we were allowed to do it using the ternary operator . . . the solution could be done in a single statement:   Off to code... Have a great evening!  ~d

Thank you

Use neither the ?: operator for that sort of statement, nor an if‑else. This (old style guide link) is what you should write:-In their example with ?:, x and y are not booleans.
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic