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.
Related
I am trying to call a variable from another class in another to the second java file
public class selectFile {
public void hdrFile(){
String hdrName = "directory";
readImage sendVari = new readImage();
sendVari.setprintHDR(hdrName);
}
}
public class readImage {
private String hdr_dir;
public static void main(String[] args){
selectFile call_vari = new selectFile();
call_vari.hdrFile();
}
public void setprintHDR(String hdr_dir){
this.hdr_dir = hdr_dir;
}
public String getprintHDR(){
return hdr_dir;
}
public void anotherMethod(){
System.out.println(getprintHDR());
}
}
I am doing this because I want to use "anotherMethod" Method in second in the third file, but when I am testing in the second java file by printing it to the terminal "anotherMethod" cannot print any hdr_dir even I return hdr_dir. But if I check "setprintHDR" by printing it to the command everything seem fine, it returns "directory"
public class Main {
public static void main(String[] args){
readImage call_vari = new readImage();
call_vari.anotherMethod();
}
}
Since you want to use the updated value in another object( basically trying to share the value between multiple objects), you should keep your variable hdr_dir as static. Static vs Instance Variables: Difference?
You were currently using the variable as instance one due to which if one object updates the value, it will remain specific to that object only.
For your main class,
public class Main {
// private String hdr_dir;
public static void main(String[] args){
int res = 0;
selectFile call_var = new selectFile();
call_var.hdrFile();
readImage call_vari = new readImage();
// call_var.anotherMethod();
// call_vari.setprintHDR("printHDR");
call_vari.anotherMethod();
}
}
and the output is
value of hdr_dir is passed is -------directory // doing some console logging
value of hdr_dir assigned is -------directory
directory
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();
I have this project of an Online Store. The class OnlineStore is where the main method is, that starts the program. I also have 3 classes, User, Item andPackage, with some inherited classes.
I store all users, items and Packages in linked lists.
I created instances in the class OnlineStore inside the main method but I want to be able to access to them every moment; The class Item sould be able to access this linked list and remove an item that has been sold.
public class OnlineStore{
public static void main(String[] args) {
LinkedList<User> users = new LinkedList<User>();
LinkedList<Item> itemsSold = new LinkedList<Item>();
LinkedList<Item> items = new LinkedList<Item>(
LinkedList<Package> packages = new LinkedList<Package>();
}
}
//Then I create some instances of Items Users and call their methods of buying,
//loging in, etc..
//If a item is buyed:
public class Buyer extends User {
//ATTRIBUTES
private String accountNumber;
private LinkedList<Item> boughtItems;
//CONSTRUCTOR
public Buyer(String n, String id, String pass, String a){
super(n, id, pass);
accountNumber = a;
}
//METHODS
public void buy(Item i){
boughtItems.add(i);
//Here I need to acces the first class and remove from availableItems
items.remove(i);
}
}
Thanks for your help!
John R.
Try something like this:
public class OnlineStore{
public static LinkedList<User> users = new LinkedList<User>();
public static LinkedList<Item> itemsSold = new LinkedList<Item>();
public static LinkedList<Item> items = new LinkedList<Item>();
public static LinkedList<Package> packages = new LinkedList<Package>();
public static void main(String[] args) {
}
}
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);
}
}
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
}