1

in my code i have around 150 users details to save or trivers many time.

Which one is better approach:

save user details in list or in objects;

Map<String, List<String>> users= new Map<String, List<String>>();
List<String> data = new ArrayList<String>();
data.add(Name);
data.add(address);
data.add(phone);
users.put(userID,data);

Or

Map<String, UserData> users= new Map<String, UserData>();

public class UserData {
    Public String name;
    Public String address;
    Public String phone;
    UserData(String name,String address,String phone){
        this.name=name;
        this.address=address;
        this.phone=phone;
     }
 }  

UserData userData=new UserData("Name","ADD","123") ;
users.put(userID,userData);

Please suggest me if any other better approach i can use in my code.
and sorry for bad English.

7
  • 2
    The first one depends on the order of adding the datas into the list. The second one is much cleaner. Commented Oct 29, 2014 at 13:17
  • You only create one more object in the second example - it won't make much difference, especially for such a small number (150). Commented Oct 29, 2014 at 13:20
  • Item 55: Optimize judiciously Commented Oct 29, 2014 at 13:20
  • 1
    Object approach is better in all aspect: memory/readability/maintainability. Commented Oct 29, 2014 at 13:22
  • 1
    why don't you add userId as member in UserData, and make array of UserData? UserData users = new UserData[10]; Commented Oct 29, 2014 at 13:23

2 Answers 2

5

Java is designed around objects and the JVM handles them very well.

Design your system how it should be designed, using the tried and tested best practise of OO design. If there are performance issues (most likely there won't be), then address that problem when you get to it.

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly. And address it with real, measured data. If you can't measure it, you can't improve it.
1

If you have many, many details to set to an object the second approach is the correct one. As this is the only way to tell what data actually represents.

The first one is a simple list of items where you rely on the fact that some data is on some location. But what if a part of the data is missing ... what then ... will you insert null's instead? Not a good way to store meaningful data.

Creating classes with many properties can lead to an inconsistent state while they are being initialized. As you rely on the fact that each property is set after creation and that some properties are not null when you are using this class.

Therefore I would suggest to use the builder pattern in such case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.