Joshua Bakker Joshua Bakker - 3 months ago 10
Java Question

Java - does the collection always change when I get a value and change

I'm writing a program now in Java which is kind of like a server. I got a

MemberController
, in
MemberController
it gets
Members
from the database OR from the cache (to speed up process). This is an example of how it looks:

public class MemberController {

private final TMap<Integer, Member> members;

public MemberController() {
this.members = new THashMap<>();
}

public Member getMemberByID(int id) {
if (members.containsKey(id)) {
return members.get(id);
}

// GET DATA FROM DB
members.put(ID, MEMBER);
return MEMBER;
}


Now,
Member
contains a
BadgeController
object, which contains a
TMap
for the badges. Example of
Member
:

public class Member {
// FIELDS OF MEMBER HERE
private BadgeController badgeController;

public Member(ResultSet set) {
// SET FIELDS
}

public void InitOtherData() {
badgeController = new BadgeController(id);
}

public BadgeController getBadgeController() {
return badgeController;
}


And
BadgeController
:

public class BadgeController {

private final int memberId;
private final TMap<String, Badge> badges;

public BadgeController(int memberId) {
this.memberId = memberId;
this.badges = new THashMap<>();

// LOAD FROM DB
}

public Badge getBadge(String code) {
return badges.get(code);
}


Now, I was wondering a few things (all actually refer to the same I guess):


  1. If I get a
    Member
    from
    members
    , like
    members.get(1)
    , and I edit the object, like this:

    Member member = members.get(1);
    member.setId(1);



Will this edit the
id
inside the
TMap
as well? So if I do
members.get(1)
again, it has the updated value?


  1. If I have the member from above, and I change a value of the
    Badge
    , for example I do:



Member member = members.get(1);
member.getBadgeController().getBadge('500Members').setActive(true);


Will this result in true being printed?

System.out.println(members.get(1).getBadgeController().getBadge('500Members').getActive());


I hope my explaination is good enough. It's hard for me to explain it. I'm sorry.

Answer

Member member = members.get(1); does not copy the object but just makes a shortcut (reference). Changing member affects the item in your set as well.

To create an effective copy you have to make your object inherit from the Cloneable interface and call the clone() method on it to get a copy.