How to reference variables in a new class? - java

I'm writing a program which consists of multiple classes. One class is called "User" and the other one is called "userGroup". I'm trying to import a variable which is contained within a constructor from the User class and use it in the userGroup class.
I've tried the following code:
User userRetrieve = new User();
userRetrieve.User();
This code doesn't seem to work, although I have seen in various tutorials that this is how you would retrieve data from another class. The second line has ".User()" because the constructor is also called User but I am not sure if this is correct and even if it was the initial problem of the program not recognizing the first line would still remain.
I'll show the code form both classes for extra information which may show where I have gone wrong:
User class:
public class User {
String username;
String userType;
String name;
public User() {
username = "x";
userType = "y";
name = "z";
}
public String getUsername() {
return username;
}
public String getUserType() {
return userType;
}
public String getName() {
return name;
}
public String setUserType(String admin) {
return userType = admin;
}
}
userGroup class:
import java.util.ArrayList;
public class userGroup {
String User;
ArrayList<User> userArray = new ArrayList<>();
Integer user0;
public void addSampleData() {
userArray.add(new User());
}
public void getUser(User user0) {
user0 = userArray.get(0);
}
public void printusername() {
System.out.println(user0.getUserName()); // x
}
}
I'm trying to use the username and userType variables in the constructor from the User class.
P.S Apologies for any formatting/indentation errors.

You have misunderstrood some concepts. Firstly the User() method is the constructor so when you do User user = new User() that method is called. I suggest this change to your user class
public class User {
private String username;
private String userType;
private String name;
// Use constructor to pass data to your class
public User(String username, String userType, String name) {
this.username = username;
this.userType = userType;
this.name = name;
}
public String getUsername() {
return username;
}
public String getUserType() {
return userType;
}
public String getName() {
return name;
}
public String setUserType(String admin) {
return userType = admin;
}
}
Now you can create your array and add a user, then retrieve its information
List<User> users = new ArrayList<User>();
users.add(new User("x", "y", "z"));
users.get(0).getUsername(); // returns "x"

Make a list of users
List<User> users = new ArrayList<User>()
Add a user
users.add(new User());
Get a user (lists and arrays are zero-indexed)
User user0 = users.get(0);
Print some properties
System.out.println(user0.getUserName()); // x

You could use the get methods you created in the constructor class?
So if you want to get the username and the userType just create a new variable using the get method
User userRetrieve = new User();
String username = userRetrieve.getUsername();
String userType = userRetrieve.getUserType();
Or alternatively you could just directly access the variables:
User userRetrieve = new User();
String username = userRetrieve.username;
String userType = userRetrieve.userType;

User userRetrieve = new User();
On this line you are instantiating a new object of type Person,
you do this by calling the constructor associated with this particular class.
After you have done this it is possible to acces parameters by calling the various methods you have defined in the Person class. So in your case you should use userRetrieve.getUsername() and so on.. you will however need to declare a variable in the calling class to store these values in.

Related

Morphia - custom field with custom reader and writer

I want to add a custom type of field that will have a default behaviour.
my purpose is to handle all type of secret fields:
for example:
I have password field on user class, and I want password field to be encrypted on some way, so instead of:
#Entity
public static class User {
String name;
String pwd;
String pwdToken
public User() {
}
public User( string name, string password ) {
super();
this.pwd = password;
}
}
and then managing the decrypt and encrypt from outside - service or controller
I would have something like that:
#Entity
public static class User {
String name;
SecretField pwd;
public User() {
}
public User( string name, string password ) {
super();
this.name = name;
// this.pwd.set(password)
}
}
public final class SecretField implements Serializable {
private static final long serialVersionUID = 1L;
private String encryptedContent;
private String token;
public SecretField(String content) {
this.token = generateToken();
this.encryptedContent = decrypt(content, this.token);
}
// when especially called the decrypted pwd will be returned
public decrypt(){
decrypt(encryptedContent, token)
}
//here I should override the default output object - return this.encryptedContent instead of whole object
//???
}
This way, every time I have a secret field I can just use this class and the encrypting will be done automatically, And I won't need to manage the on each controller seperatly.
On update and insert, the password will be sent as decrypted string from client and on get the enrypted string will be returned.
Is it possible with morphia?
You can write a custom codec in 2.0 to do that for you. Prior to that you could write a life cycle event handler to do that. The docs for that can be found at https://morphia.dev

Most efficient way to compare a list of strings to a list of objects with a string field

So I have this problem that actually occurs a lot in my code but here's the easiest example of it. The problem is I have an object which contains a list of Strings which correspond to the 'name' or 'id' or 'username' (it depends) fields of another object. So, for example, I have a PublishGroupType object which looks like this:
public class PublishGroupType {
protected List<String> username;
protected String name;
public List<String> getUsername() {
if (username == null) {
username = new ArrayList<String>();
}
return this.username;
}
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
//etc...
}
and a UserModel object that looks like this:
public class UserModel {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
userData.put(UserColumns.USERNAME.getUserColumnName(), username);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
userData.put(UserColumns.PASSWORD.getUserColumnName(), password);
}
//etc
}
Now because of other reasons I am not allowed to make major changes to PublishGroupType so I cannot directly change the list to contain a list of UserModels instead of Strings. But, I can add a Group field to UserModel and I can create a wrapper class GroupModel which looks like this:
public class GroupModel{
public PublishGroupType publishGroupType;
public List<UserModel> users;
public GroupModel(PublishGroupType publishGroup) {
this.publishGroupType = publishGroup;
List<UserModel> allUsers = userManagementClient.getAllUsers();
//populate the users here from a list of all users
for(UserModel user : userManagementClient.getAllUsers()){
if(publishGroupType.getUsername().contains(user.getUsername())){
users.add(user);
user.setGroup(this);
}
}
}
}
Now, the problem is there are many times more users in the list of all users than there are in a Group, so this is really inefficient to loop through all users for each group. Keep in mind that this is one small and simple example of a problem that happens A LOT all over my code base. Is there a better way to match UserModels with their string Usernames?
First, I'm a little confused as to whether your question is generic like the title of your post:
compare a list of strings to a list of objects with a string field
or if it's specific like the last line in your post:
Is there a better way to match UserModels with their string Usernames?
I'm going to answer the latter.
Here's what I would suggest - have the userManagementClient maintain a HashMap whose keys are the usernames and whose values are the UserModel objects. Then you can modify the class (not sure of the name, you didn't provide it) whose instance you called userManagementClient to provide a method to get the UserModel based on a String parameter (the username):
public UserModel getUserModel(String username){
return userMap.get(username);
}
Then you can change your loop from this:
for(UserModel user : userManagementClient.getAllUsers()){
if(publishGroupType.getUsername().contains(user.getUsername())){
users.add(user);
user.setGroup(this);
}
}
to this:
for(String user : publishGroupType.getUsername()){
UserModel userModel = userManagementClient.getUserModel(user);
if(userModel != null){
users.add(user);
user.setGroup(this);
}else{
//handle missing user appropriately
}
}
Now you're only looping through the users associated with the publishGroupType instead of all the users and you're able to obtain the UserModel without using contains over and over.
One final thought - this question probably would have been a better fit for codereview.stackexchange.com since the code works without errors.

How to assign properties to a user in an Array List?

So far I have created an Array List which only currently consists of one user. For my assignment, I have been asked to print out properties for that user such as its username and userType. As far as I aware I have created an enhanced for loop that would print out these properties if only they were assigned. My question is how would I go about assigning these properties to my user? I have created a UserGroup class in which the array list resides in and a User class in which some details about the User is specified however I am not quite sure if the User class is correct for what I am trying to achieve. Here is the code for both classes:
UserGroup:
package main;
import java.util.ArrayList;
public class UserGroup {
ArrayList<User> userGroup = new ArrayList<>();
User userOne;
public void addSampleData(String username, String userType, String name) {
userGroup.add(new User("LeeB", "Staff", "Lee"));
}
public User getUser(int index) {
return userGroup.get(0);
}
public void printusername(){
for (User x : userGroup)
System.out.println(x);
}
}
User:
package main;
class User {
String username;
String userType;
String name;
User(String username, String userType, String name) {
this.username = username;
this.userType = userType;
this.name = name;
}
public String getUsername() {
return username;
}
public String getUserType() {
return userType;
}
public String getName() {
return name;
}
public String setUserType(String admin) {
return userType = admin;
}
}
Main method:
package main;
public class Main {
public static void main(String[] args) {
for (int counter=2; counter<=40; counter+=2) {
System.out.println(counter);
}
System.out.println("For loop complete.");
int counter = 1;
int increment = 2;
int loopexeccounter = 0;
while (counter <= 500) {
loopexeccounter = loopexeccounter + 1;
System.out.println(counter);
counter = counter + increment++;
}
System.out.print("This loop iteratted "+loopexeccounter+" times.");
}
public Main() {
UserGroup userGroupObject = new UserGroup();
System.out.println(userGroupObject.getUser(0));
}
}
Ignore everything above the latest method, it's just some examples of loops that they wanted us to print out.
Updated version, no errors but user(0) isn't being printed out.
So far I have created an Array List which only currently consists of one user.
Actually, user0 is never assigned. It's null, so you're only going to be adding null into the list.
You do not need user0 variable.
ArrayList<User> userGroup = new ArrayList<>();
User userOne;
public void addSampleData(String username, String userType, String name) {
userGroup.add(new User(username, userType, name));
}
Then,
public User getUser(int index) {
return userGroup.get(index);
}
If you want the first user, call that method with 0 as the parameter.
As far as this is concerned, it's fine, but see How do I print my Java object without getting "SomeType#2f92e0f4"?
public void printusername(){
for (User x : userGroup)
System.out.println(x);
}
Alternatively, if you just want x's username, then print that instead of the entire object
Slightly more advanced option, since the Group essentially is a list of users.
public class UserGroup extends ArrayList<User> {
Or, you don't really need that class unless you add more specialized methods than add, get, and print

What object to return in the following arraylist

I am trying to understand array list and have read and searched online for a few examples. I am unable to understand what OBJECT should this arraylist return? I know the arraylist has object type user. On returning it I encounter the following error
Type mismatch: cannot convert from Boolean to User
private ArrayList<User> users; // list of users
public User createUser(String name, String address) {
user = new ArrayList<User>();
users.add(new User(name, address));
return null; <-- not sure what to return here
}
Also User is another class.
public class User {
private String name; // user name
private String address;
/*
* constructor method
*/
public User(String name, String address) {
// initialize the instance variables
this.name = name;
this.address = address;
}
Being this
public User createUser(String name, String address)
your method signature, you must return an object of type User or one of its subclasses.
I think this is what you're trying to achieve
private ArrayList<User> users; // list of users
public User createUser(String name, String address) {
User u = new User(name, address);
users = new ArrayList<User>();
users.add(u);
return u;
}
but notice that by executing
users = new ArrayList<User>();
inside the method, you will reset the list every time: you will always have a list of one element. Initialize your list only once, instead
private ArrayList<User> users= new ArrayList<User>(); // list of users
public User createUser(String name, String address) {
User u = new User(name, address);
users.add(u);
return u;
}

Making the arraylist get method work and other problems

I am coding in blueJ. My objectives are this: 1)Write a User class
A User:
has a username e.g 'fj3'
has a userType which can be: 'user', 'editor' or 'admin'
has a name e.g 'Francis'
has a constructor which takes the username, userType and name as parameters
has a getUsername() method
has a getUserType() method
has a getName() method
has a setUserType() method which takes one of the user types as a parameter
2)Write a UserGroup class
The UserGroup class must have an ArrayList of Users.
Write a constructor for the UserGroup class. It should instantiate the ArrayList.
In UserGroup write a method called .addSampleData() which creates 10 Users and using the ArrayList's add() method put the 10 new User objects into the ArrayList.
In UserGroup write a getUser method which takes an int as a parameter and returns the User in that slot of the ArrayList.
In UserGroup write a printUsernames() method in UserGroup:
Using an enhanced for loop (see above), loop through the ArrayList and print the username and userType of each user in the ArrayList.
What I have so far is:
package user;
public class User{
public enum UserType{
ADMIN, EDITOR, USER;
}
private String id;
private UserType userPermissions;
private String actualName;
public User(String username, UserType userType, String name){
id = username;
userPermissions = userType;
actualName= name;
}
public String getUsername(){
return id;
}
public UserType getUserType(){
return userPermissions;
}
public String getName(){
return actualName;
}
public void setUserType(UserType input){
userPermissions = input;
}
}
And my UserGroup class:
package user;
import java.util.*;
import user.User.UserType;
public class UserGroup{
private ArrayList<User> people;
public UserGroup(){
people = new Arraylist<User>();
}
public static void addSampleData(String username, UserType userType, String name){
people.add(new User(username, userType,name));
}
public User get(int){
return User;
}
public void printUsernames(){
for (User user: groupArray){
System.out.printf("%s %s\n", user.getUsername(), user.getuserType);
}
}
}
This is obviously far from being complete but I am completely stuck. My first problem is that I am unsure how to write the get method for this. Please help me with this!! I think my User class is fine but my UserGroup class is nowhere near completing all the objectives and I don't know how to do them!!
Looks good so far, some corrections:
The addSampleData()method should not be static, as it uses a non-static member of the class. The request also states it to add the sample data itself.
The getUser() is pretty straight forward then.
The printUsernames()method uses an unknown member.
public void addSampleData() {
people.add(new User("pe3", UserType.ADMIN,"Peter"));
people.add(new User("u987", UserType.EDITOR,"Udo"));
people.add(new User("frank123", UserType.USER,"Frank"));
// repeat ...
}
public User getUser(int idx) {
return people.get(idx);
}
public void printUsernames(){
for (User user: people){
System.out.printf("%s %s\n", user.getUsername(), user.getuserType);
}
}
In a main method then:
UserGroup grp = new UserGroup();
grp.addSampleData();
grp.printUsernames();
User u1 = grp.getUser(0);

Categories