The value in the map taken by SprinEL is always null - java

what I want to ask is that in the process of using springel, I want to get the value in the map, but no matter how I get it, my value will always be null
#Data
#Component("workersHolder")
public class WorkersHolder {
private Map<String, Integer> salaryByWorkers = new HashMap<>();
public WorkersHolder() {
salaryByWorkers.put("John", 35000);
salaryByWorkers.put("Susie", 47000);
salaryByWorkers.put("Alex", 12000);
salaryByWorkers.put("George", 14000);
}
public static void main(String[] args) {
// 35000
System.out.println(new WorkersHolder().salaryByWorkers.get("John"));
}
}
#Data
#Component
public class GetData {
#Value("#{workersHolder.salaryByWorkers['John']}")
private Integer johnSalary;
#Value("#{workersHolder.salaryByWorkers['George']}")
private Integer georgeSalary;
#Value("#{workersHolder.salaryByWorkers['Susie']}")
private Integer susieSalary;
public static void main(String[] args) {
// null
// Hope this line can output 35000
System.out.println(new GetData().johnSalary);
}
}
The line in bold prints 35000 as expected, but is null
May I ask if there is a step I did wrong, any ideas are welcome to provide to me, thank you

Related

Converting an Object list to a Queue

How do I convert a List of objects to a Queue and still be able to access their variables?
First I have a main class that creates instance classes of ClassTwo and gives them a unique ID (just hard coded it for the example)
public class ClassOne
{
static List<ClassTwo> processList = new ArrayList<ClassTwo>();
public static void main(String[] args)
{
processList.add(new Process(1));
processList.add(new Process(2));
processList.add(new Process(3));
}
}
ClassTwo:
public class ClassTwo
{
int id;
public ClassTwo(int tempID)
{
id = tempID;
}
}
How would I convert my List to a Queue so that I can still access each object's ID in class one?
I tried something like:
public class ClassOne
{
static List<Process> processList = new ArrayList<Process>();
public static Queue<Object> processQueue = new LinkedList<Object>();
public static void main(String[] args)
{
processList.add(new Process(1));
processList.add(new Process(2));
processList.add(new Process(3));
ConvertToQueue();
}
ConvertToQueue(List<Process> process)
{
//covert here..
}
}
but I'm not sure exactly how to then convert it to a Queue, so i can still call variable 'id' from each ClassTwo object. Help would be appreciated!
You can use this :
Queue<Process> queue = new LinkedList<>(processList);
When you make this, you can still access to every element of the list, because they are all the same instances.

Creating multiple objects using the same instance

I just saw this tutorial creating multiple objects using the same instance by applying the DAO pattern and tried it in a simple console, but I always get this message java.lang.NullPointerException I'm now confused, as far as I know, a constructor can be used once only, and the object will be immutable. Kindly look at this:
Fighter.java
public class Fighter {
private String style;
public Fighter() {}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
}
FightersDAO.java
public class FightersDAO {
public List<Fighter> getFighters(){
List <Fighter> fighter = new ArrayList<>();
String [] styles= { "Karate", "Sumo", "Pro-Wrestling" };
for(int i=0; i < styles.length; i++) {
Fighter temp = new Fighter();;
temp.setStyle(styles[i]);
fighter.add(temp);
}
return fighter;
}
}
Demo.java
public class Demo {
private static FightersDAO fighterDAO;
public static void main (String [] args) {
List <Fighter> fighters = fighterDAO.getFighters();
for(Fighter e: fighters) {
System.out.println(e.getStyle()); //this should output the objects, but nothing shows
}
}
}
Why is it null? What part did went wrong
The variable fighterDAO is never initialized. Therefore you get a NPE here:
List <Fighter> fighters = fighterDAO.getFighters();
To fix that use:
private static FightersDAO fighterDAO = new FightersDAO();
private static FightersDAO fighterDAO;
I think there is a problem because it is not initialized.
Change it:
private static FightersDAO fighterDAO = new FightersDAO();
In your code
private static FightersDAO fighterDAO;// here is not initialized. its just a declaration so fighterDAO = null;
while executing below code will throw exeption
List fighters = fighterDAO.getFighters();// means null.getFighters();
Below is the correct code
package aks;
import java.util.List;
public class Demo {
private static FightersDAO fighterDAO= new FightersDAO();
public static void main (String [] args) {
List <Fighter> fighters = fighterDAO.getFighters();
for(Fighter e: fighters) {
System.out.println(e.getStyle());
}
}
}
You can analyse this by just debuggin on eclise or any IDE
If you want same instance use below code
private static FightersDAO fighterDAO = new FightersDAO();

Return a string value to the pass-in varibale from the argument in a function

I want the pass-in variable "aaa" to be returned the value from the argument of the function. I really need my argument in the function to be defined as String, and want whatever change of the argument in the function to be return to the pass-in variable.
How do I make this happen in Java? If anyone could help I will appreciate!
public class DeppDemo {
private String aaa;
public void abc(String aaa) {
aaa = "123";
}
public static void main(String[] args) {
DeppDemo demo = new DeppDemo();
demo.abc(demo.aaa);
System.out.println(demo.aaa);
}
}
You cannot do it like this: String class in Java is immutable, and all parameters, including object references, are passed by value.
You can achieve the desired result in one of three ways:
Return a new String from a method and re-assign it in the caller,
Pass mutable StringBuilder instead of a String, and modify its content in place, or
Pass an instance of DeppDemo, and add a setter for aaa.
Here are some examples:
public class DeppDemo {
private String aaa;
private StringBuilder bbb = new StringBuilder();
public String abc() {
return "123";
}
public void def(StringBuilder x) {
x.setLength(0);
x.append("123");
}
public static void main(String[] args) {
DeppDemo demo = new DeppDemo();
demo.aaa = demo.abc(); // Assign
demo.def(demo.bbb); // Mutate
System.out.println(demo.aaa);
}
}
It's really unclear what you're asking, but it sounds like you're trying to change the content of a variable passed into a function. If so, you can't in Java. Java doesn't do pass-by-reference.
Instead, you pass in an object or array, and modify the state of that object or array.
public class DeppDemo {
public void abc(String[] aaa) {
aaa[0] = "123";
}
public static void main(String[] args) {
String[] target = new String[1];
DeppDemo demo = new DeppDemo();
demo.abc(target);
System.out.println(target[0]);
}
}
But if you're asking how to update the aaa field using the aaa argument, then you need to qualify your reference to the field using this., since you've used the same name for both. Or change the name of the argument.
public class DeppDemo {
private String aaa;
public void abc(String aaa) {
this.aaa = aaa;
}
public static void main(String[] args) {
DeppDemo demo = new DeppDemo();
demo.abc("New value");
System.out.println(demo.aaa);
}
}

Get String From Another Method?

I have two methods, the first one creates a string, then I want to use that string in the second method.
When I researched this, I came across the option of creating the string outside of the methods, however, this will not work in my case as the first method changes the string in a couple of ways and I need the final product in the second method.
Code:
import java.util.Random;
import java.util.Scanner;
public class yaya {
public static void main(String[] args) {
System.out.println("Enter a word:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
Random ran = new Random();
int ranNum = ran.nextInt(10);
input = input + ranNum;
}
public void change(String[] args) {
//more string things here
}
}
Create an instance variable:
public class MyClass {
private String str;
public void method1() {
// change str by assigning a new value to it
}
public void method2() {
// the changed value of str is available here
}
}
You need to return the modified string from the first method and pass it into the second. Suppose the first method replaces all instances or 'r' with 't' in the string (for example):
public class Program
{
public static String FirstMethod(String input)
{
String newString = input.replace('r', 't');
return newString;
}
public static String SecondMethod(String input)
{
// Do something
}
public static void main(String args[])
{
String test = "Replace some characters!";
test = FirstMethod(test);
test = SecondMethod(test);
}
}
Here, we pass the string into the first method, which gives us back (returns) the modified string. We update the value of the initial string with this new value and then pass that into the second method.
If the string is strongly tied to the object in question and needs to be passed around and updated a lot within the context of a given object, it makes more sense to make it an instance variable as Bohemian describes.
Pass the modified string in the second method as an argument.
create a static variable used the same variable in both the method.
public class MyClass {
public string method1(String inputStr) {
inputStr += " AND I am sooo cool";
return inputStr;
}
public void method2(String inputStr) {
System.out.println(inputStr);
}
public static void main(String[] args){
String firstStr = "I love return";
String manipulatedStr = method1(firstStr);
method2(manipulatedStr);
}
}
Since you mentioned that both methods should be able to be called independently, you should try something like this:
public class Strings {
public static String firstMethod() {
String myString = ""; //Manipulate the string however you want
return myString;
}
public static String secondMethod() {
String myStringWhichImGettingFromMyFirstMethod = firstMethod();
//Run whatever operations you want here and afterwards...
return myStringWhichImGettingFromMyFirstMethod;
}
}
Because both of these methods are static, you can call them in main() by their names without creating an object. Btw, can you be more specific about what you're trying to do?

Java - Passing Arrays in Methods, Variables Not Recognized

I have been stuck on this one for days, but I have broken it down here. What I need to do is to create an array of accounts with about 9 variables each (AccountID, WithdrawlDates, etc.) that the user can input in a command prompt. From the createAccount() method I can send an instance of user and a accountNum, but the user is not recognized on the receiving setAccount method.
Here's the code:
class User{
private int accountID;
User( int id )
{
accountID = id;
}
static void setAccountID(User user[], int accountNum)
{
user.accountID = accountNum; //accountID is not recognized here
}
static void getAccountID(User user){System.out.println(user.accountID);}
}
class TestUser
{
public static void main(String[] args)
{
createAccount();
}
static void createAccount(){
User[] user = new User[2];
user[0] = new User(25);
User.setAccountID(user, 2001);
}
}
I am open to changing the flow of this, but I don't know where to start.
Thanks!
To access the elements of an array instead of doing something with the array itself you use square brackets like so:
user[userIndex]
from there you can either change the element like this
user[userIndex] = new User(id);
or access/modify something about the element itself like this
user[userIndex].accountID = whatever;
Additionally, your use of static in the setAccountID is confusing things. A static method cannot know anything about accountID because accountID is a part of a uniquely created object where the static method belongs to the class, and not any particular object. If it must be static for some reason, you will need to change the method to look something like this
static void setAccountID(User user[], int userIndex, int accountNum)
{
user[userIndex].accountID = accountNum;
}
but the following would be much better, since you know the user inside the array anyway:
void setAccountID(int accountNum)
{
this.accountID = accountNum;
}
called like this:
user[userIndex].setAccountID(accountNum);
There's no reason to pass an array of User objects. Try this instead:
class User{
private int accountID;
User( int id )
{
accountID = id;
}
static void setAccountID(User user, int accountNum)
{
user.accountID = accountNum; //accountID is not recognized here
}
static void getAccountID(User user){System.out.println(user.accountID);}
}
class TestUser
{
public static void main(String[] args)
{
createAccount();
}
static void createAccount(){
User user = new User(25);
User.setAccountID(user, 2001);
}
}
EDIT: If you need to maintain an array of users as #Luiggi Mendoza suggests in his comment, just pass a single array element to setAccountID():
static void createAccount(){
User[] user = new User[2];
user[0] = new User(25);
User.setAccountID(user[0], 2001); // set id for first User
}

Categories

Resources