I have an Object named Person(name, surname, age)
This Object is populated with values from a local file.
But i want to keep this object visible through the app since there is a GUI for adding new values to this.
I was trying to put an Interface like this but doesn't work
public interface MyInterface{
public List<Person> myPersonObj = new ArrayList<Person>();
}
and to call it in app like MyInterface.myPersonObj
Can someone help me?
Thanks
You have to declare the variable static, e.g.
public static (final) List<Person> persons = new ArrayList();
For more information, read about the Singelton Pattern
Because it's in an interface it will automatically be final (read-only), thus you probably want to put it in a class instead:
public class AnyClass{
public static List<Person> myPersonObj = new ArrayList<Person>();
}
Then you can do:
AnyClass.myPersonObj
to access it.
make the list static inside the class where you populate it.
class Populate{
public static List<Person> myPersonObj;
public static void setMyPersonObj(List<Person> inst){
myPersonObj =inst;
}
public static List<Person> getMyPersonObj(){
if(MyPersonObj!=null){
return myPersonObj;
}
else {
return new ArrayList<Person>();
}
}
//populate it
}
class SomeOther {
public static void someMethod(){
Populate.getMyPersonObj();
}
}
Related
Basically, when I passed arguments in Java, I knew it was passing only value.
However, the following code shows that the add method executed on SubClass's SubMethod affects ArrayList of MainClass.
MainClass.java
public class MainClass{
public satatic void main(String[] args){
List list = new ArrayList<>();
SubClass subClass = new SubClass(list);
subClass.subMethod();
System.out.println(list) // Why added value???
}
}
SubClass.java
public class SubClass{
private List list;
public SubClass(List list){
this.list = list;
}
public void subMethod(){
list.add(1);
list.add(2);
}
}
When I did the same thing with a HashMap's put, there was no effect on the HashMap of the MainClass.
I would like to know why only ArrayList is causing these results and what is happening inside Java.
Update
The code for the hashmap version is as follows:
MainClass.java
public class MainClass{
public satatic void main(String[] args){
Map map = new HashMap<>();
SubClass subClass = new SubClass(map );
subClass.subMethod();
System.out.println(map) // Not putting value
}
}
SubClass.java
public class SubClass{
private Map map;
public SubClass(Map map){
this.map= map;
}
public void subMethod(){
map = someGenerationHashMap(arg1, arg2);
}
}
It's not about ArrayList. Any object you pass as an argument can be modified. What is passed by value is the address of the object, not the object itself.
In the Map version, you are not making any operation that could modify it. In the list version instead, you are making an add.
Make sure not to confuse objects with primitives. For example, make sure not to confuse int with Integer.
I have a problem with a task I have to do. I need to create class Company and write few methods (such as hire, fire, etc.) for Employee class objects.
Those are my classes and methods:
public class Company{
ArrayList <Employee> alist= new ArrayList<Employee>();
public void hire(Employee e) {
int i=0;
boolean k=false;
while(i<alist.size()) {
if (e.getLastName().equals(alist.get(i).getLastName())) {
k=true;
i++;
}
}
if (k==false) alist.add(e);
else System.out.print("Employee already exists");
}
}
public class Employee{
protected String lastname; //protected for subclasses
protected double jobposition;
public Employee(String lastname,double jobposition) {
this.lastname=lastname;
this.jobposition=jobposition;
}
public String getLastName() {
return lastname;
}
And subclass which extends Employee:
public class OfficeWorker extends Employee {
float pay, bonus;
public OfficeWorker(String lastname,double jobposition,float pay,float bonus) {
super(lastname,jobposition);
this.pay=pay;
this.bonus=bonus;
}
}
I wanted to use ArrayList to do this, but it crashes in main class and I get message "The method hire(Employee) is undefined for the type ArrayList":
public static void main(String[]args) {
ArrayList <Employee> list = new ArrayList <Employee>();
Employee e1 = new OfficeWorker("Smith",0.5,2000,50);
list.hire(e1);
}
Why can't I do this like that?
Your main method should be like:
public static void main(String[]args) {
Company company = new Company();
Employee e1 = new OfficeWorker("Smith",0.5,2000,50);
company.hire(e1);
}
As you have already written method hire() in class Company which adds the Employee in the ArrayList <Employee> alist.
There is NO way you can create your own method in Java ArrayList class.
ArrayList list = new ArrayList ();
ArrayList don't have hire method.
In a class you can access the method availabe in that method.And that also depends upon access modifier and where you are aceesing the method.
To access a non-static public method you have to create object and call method on that object
SomeClass c=new SomeClass();
c.m();
For static public method you can call directly
SomeClass.m();
hire() method is defined as part of Company Class.
it should be as below.
Company xyz = new Company();
xyz.hire(e1);
What's happening is that you are calling the method hire directly into the ArrayList object, instead of that, create an object called Company, then, once it's created, call the method of hire in the Company, as the Company already has the property of ArrayList in it.
public static void main(String[]args) {
Company company = new Company();
Employee e1 = new OfficeWorker("Smith",0.5,2000,50);
company.hire(e1);
}
Hope it helps!
StackPeople, I have a question. What statement could help me implement the right class before inserting it to the ArrayList. I have declared Nurse and Pilot which are Employees objects.
I want each implementation of my class ArrEmp to store different Employees objects
example: arrEmpNurses, arrEmpPilots,... after my class gets an example in the constructor
What statement helps?? Or should I re think the problem.
Thanks for your help.
THE PROBLEM IS TO FILL THE ARRAY WITH THE RIGHT CLASS (IT WILL READ FROM PLAIN TEXT AND IT NEWS TO BE NOTIFIED WhAT CLASS TO IMPLEMENT TO ADD IT)
"This code compiles, just copy paste."
import java.util.*;
public class ArrEmp {
String[][] data={ {"E1"}, {"Maria"}, {"E2"}, {"John"} }; //Data
Employee x;
static Nurse nancy= new Nurse("01","Nancy");//this are just examples
static Pilot peter= new Pilot("02","Peter");//so the arrayEmp knows what type of employee create
ArrayList arr;
public ArrEmp(Employee x){
this.x=x;
arr= new ArrayList();
fillList();//with data array
}
public void fillList(){// I would like to fill the List with Nurses. How could i do it?
//for( String[] param: data )
//arr.add( ) //insert helpfull statement here
//the goal is to have an array of Pilot and another of Nurses
}
public static void main(String[] args) {
ArrEmp arr1= new ArrEmp( nancy );
ArrEmp arr2= new ArrEmp( peter );
}
public static class Employee {
String cod;
public Employee(String cod){
this.cod=cod;
}
}
public static class Nurse extends Employee{
String name;
public Nurse(String ... para){
super(para[0]);
this.name=para[1];
}
}
public static class Pilot extends Employee{
String name;
public Pilot(String ... para){
super(para[0]);
this.name=para[1];
}
}
}
I asked the question this way because data is actually read from Disk and ArrEmp has no idea what Employee he is reading. i need to provide an example so it builds the right employee and then insert it into the array. so new ArrEmp( nancy ) reads the file and builds Nurses and store them but new ArrEmp( nancy ) reads a file and loads Pilots on it.
EDIT SOLUTION: ESCENTIALLY I WILL CREATE A GENERIC ARRAYLIST EXTENDS EMPLOYEE, and extending classes for each Emlployee object...
Why not use generics? See: Java generics - ArrayList initialization
Essentially use
ArrayList<Nurse>
Instead of ArrayEmp(Nancy) to say it will only contain Nurses, then the language will take care of enforcing it.
public static class Employee {
String name;
int ID = 0;
public Employee(String name){
this.name = name;
}
}
Just use ID's to denote the differentiation between all of them? You can create an ENUM and fill in legible names for differentiating between different objects. It's faster then string comparing and using instanceOf.
public static class Pilot extends Employee{
int ID = 1;
public Pilot(String name){
this.name = name;
}
}
EDIT:
public ArrEmp(Employee x){
if (x.ID == 1) // add to the list you want
else if (x.ID == 2) // add to list you want
....
}
Hey guys I just have a quick question about initializing an arraylist
This is just a small piece of code I'm doing
public class OrderManager {
ArrayList<Order>orders = new ArrayList<Order>();
public OrderManager() {
}
public OrderManager(ArrayList<Order> orders) {
orders = new ArrayList<Order>();
}
using a variable orders, and then declaring orders = new correct? Or is this going to be two different instances and when I try to add things to it its not going to work?
Or since OrderManager is going to take an arraylist does it even make sense?
I haven't tested it yet, I just started writing this code and have ran into this problem before where I couldn't add to the list properly and believe it was because of a error similar to this just checking to try and get it right to start with.
public class OrderManager {
private ArrayList<Order>orders;
public OrderManager() {
this(new ArrayList<>());//call constructor
}
public OrderManager(ArrayList<Order> orders) {
this.orders = orders;
}
.
.
//more methods here for example getters and/or setters for orders
}
This is the proper way. Also consider using List rather than ArrayList cause in future if you want not to be ArrayList and for example be LinkedList you don't have to modify this class. Programming to an interface concept.
So your class would look like:
public class OrderManager {
private final List<Order>orders;
public OrderManager() {
this(new ArrayList<>());//call constructor or doing nothing is another option
}
public OrderManager(List<Order> orders) {
this.orders = orders;
}
public List<Order> getOrders(){
return orders;
}
public void addOrder(Order order){
orders.add(order);
}
}
What you are currently doing is assigning a new, empty ArrayList instead of taking the one given.
You should either do this:
public class OrderManager {
private final List<Order> orders;
public OrderManager() {
orders = new ArrayList<Order>();
}
public OrderManager(final List<Order> orders) {
this.orders = orders;
}
Which will take the reference to the List passed into the constructor. Changes to the List from outside the class will affect the List inside the class.
A more common way is to make a "defensive copy" using the copy constructor
public class OrderManager {
private final List<Order>orders;
public OrderManager() {
orders = new ArrayList<Order>();
}
public OrderManager(final List<Order> orders) {
this.orders = new ArrayList<Order>(orders);
}
Now the class has a copy of the List passed in so it will be independent of the original List.
Your second constructor is wrong.
It should be:
public OrderManager(ArrayList<Order> orders) {
this.orders = orders;
}
Constructor is what used to create a new object and initialize its class variables.
When you use new you are calling a class constructor.
There are cases when one constructor can be called from another. It's done when the calling constructor initializes a larger set of variables and uses other constructor to initialize a sub-set (so not to repeat the same code). At such cases you use this with a proper signature.
So lets say that in my entry point class (i.e the class which runs when the program starts (which has the public static void main(String args[]) function). In that class I have this variable:
private ArrayList<String> myData=new ArrayList<String>();
This class instantiates another class, which needs to have access to the myData member of the entry point class. How can it retrieve this arraylist?
Edit: To clarify, in the main() method I could do this:
SomeOtherClass myClass=new SomeOtherClass();
and then I could do:
myClass.someMethod();
however, in the myClass object, how could I perform a method/retrieve something from the entry class, which instantiated the myClass object?
It sounds like your entry point is still static when it calls some other class, but your ArrayList is a member of an instance of it. You need to move out of the static world and into instances.
I'd refactor your main method into a private construtor, and put in a new main() which launches it as a new instance.
Note that this code is very rough, but it should serve to illustrate what you need to do.
public class EntryPoint {
private ArrayList<String> myData=new ArrayList<String>();
public static void main( String[] args ) {
EntryPoint ep = new EntryPoint();
ep.init();
}
private void init() {
// Populate myData perhaps?
SomeOtherClass myClass=new SomeOtherClass();
myClass.someMethod( this );
}
public List<String> getMyData() {
return myData;
}
}
public class SomeOtherClass {
public void someMethod( EntryPoint entry ) {
List<String> data = entry.getMyData();
// do stuff with data..!
}
}
The best way to give the class you instantiate access to myData would be to pass it into the constructor when it is created.
Then, in your constructor, you can save the ArrayList into a member variable of the class.
For example, your object constructor will look like:
private ArrayList<String> myData;
public YourObjConstructor(ArrayList<String> data){
myData = data;
}
The class containing main() is just an ordinary class. In your case, you'd have to make myData public and possibly static (or, of course, add an accessor). Just like you'd do with any other class.
You could also pass an Entry object to the other class, like this:
public static void main(String[] args) {
Entry entry = new Entry();
SomeOtherClass myClass=new SomeOtherClass(entry);
// continue as before
}