get an object based on its static value - java

I am initalizing several objects of the same type that have a common field:
public class Example {
private static objectCounter = 1;
public Example () {
objectCounter++;
}
}
Since these objects are created with a for loop like this
for (int i = 0; i<5; i++) {
Example e = new Example();
}
they are not referenced.
Is there a way to get a specific object based on objectCounter value ?
Something like
//get the Example object with objectCounter==2
get(2);
Thank you

My suggestion will be saving into array:
Example store[] = new Example[5]
for (int i = 0; i<5; i++) {
store[i] = new Example();
}
And then , search for the specific object.

As stated in the comments, a static value will persist through all instances of your class.
If you want your Example to "know" it's identity, pass it in when you construct it:
Example:
public class Example {
private int id;
public Example (int val) {
this.id = val;
}
// Getters/setters
}
Probably also want to add your objects to a list to access them later, so before your for-loop:
List<Example> examples = new ArrayList()<Example>;
And create them like this:
for (int i = 0; i<5; i++) {
Example e = new Example(i);
examples.add(e);
}

Related

How to call the constructor of the members of an array in Java?

I have a class:
public class a {
public int memberA;
private int memberB;
public a (int i) {
memberA = i;
memberB = ...;
}
}
and another one:
public class b {
public a[] = new a[10]; // <-- How do I call the constructor of 'a' with a value?
...
}
I tried many things, but nothing works! My app crashes if I don't call the constructor!
You can just use a for loop to instantiate each element of the array.
public class b {
public a[] arr = new a[10];
{
for(int i = 0; i < arr.length; i++) arr[i] = new a(/*some value*/);
}
}
As an aside, always follow Java naming conventions e.g. the name of the classes should be A and B instead of a and b. Better if you use self-descriptive names.

How to change an array into an ArrayList? (generics)

I have a task to change a type of a variable into ArrayList and I need to initialize it as an ArrayList. I don't know how to do it :(
I tried this in a such way:
private ArrayList<T> warehouseContent = new ArrayList<T>();
public void registerProducts(Product... products) {
WarehouseItem[] updatedWarehouseContent = new WarehouseItem[warehouseContent.size()
+ products.length];
int i = 0;
for (; i < warehouseContent.size(); i++) {
updatedWarehouseContent[i] = warehouseContent[i];
}
for (; i < updatedWarehouseContent.length; i++) {
updatedWarehouseContent[i] = new WarehouseItem(products[i - warehouseContent.size()]);
}
warehouseContent=updatedWarehouseContent;
}
But I think it isn't correct. The source code which I need to change is below:
private WarehouseItem[] warehouseContent = new WarehouseItem[0];
public void registerProducts(Product... products) {
WarehouseItem[] updatedWarehouseContent = new WarehouseItem[warehouseContent.length
+ products.length];
int i = 0;
for (; i < warehouseContent.length; i++) {
updatedWarehouseContent[i] = warehouseContent[i];
}
for (; i < updatedWarehouseContent.length; i++) {
updatedWarehouseContent[i] = new WarehouseItem(products[i - warehouseContent.length]);
}
warehouseContent=updatedWarehouseContent;
}
Could someone give me any tips or explain me what I need to use here a generic type ArrayList?
Start by declaring the warehouseContent type as a list of WarehouseItem:
private List<WarehouseItem> warehouseContent = new ArrayList<>();
Now you can rely on ArrayList's built-in ability to grow in your registerProducts method:
public void registerProducts(Product... products) {
for (Product product : products) {
warehouseContent.add(new WarehouseItem(product));
}
}
This one loop does what the two loops and an allocation of your original implementation did. Note that copying the content of an old array into the new one is still there, but it is encapsulated in the add method of ArrayList.

Adding objects to an array

I have been looking at questions of how to add elements to an array How can I dynamically add items to a Java array?.
I do not understand how to add objects of a class type, not a datatype like String. How am I supposed to do this, when the object patient has various datatypes? What I can't get my head around, is how to put the attributes of a Patient object into an array.
Class Patient{
public Patient(String ptNo, String ptName, int procType) throws IOException
{
Patient.patientNo = ptNo;
Patient.patientName = ptName;
Patient.procedureType = procType;
}
}
Another class:
public static void main(String[] args) throws IOException
{
Patient [] patients;
Patient p = new Patient(null, null, 0);
int i = 0;
for (i = 0; i < 2; i++)
{
patients.add(p);
}
}
I understand I am missing the obvious, and only come here, after exhausting other resources.
You need to specify the array size like below
Patient [] patients = new Patient[2];
Then now add the elements like below
patients[i] = new Patient(null, null, 0)
The complete code like below
for (int i = 0; i < 2; i++)
{
patients[i] = new Patient(null, null, 0);
}
You need to access an array using the indexes
patients[i] = p;
but before that you need to initialize it as well.
Patient [] patients = new Patient[10]; // random init
Since you want them to be dynamic, try to use an ArrayList and keep adding the objects to it.
List<Patient> patients = new ArrayList<>();
patients.add(p);
Arrays are accessed via index:
Please modify your code like this.
public static void main(String[] args) throws IOException
{
Patient [] patients = new Patient[10];
Patient p = new Patient(null, null, 0);
int i = 0;
for (i = 0; i < 2; i++)
{
patients[i] = p;
}
}
You are using an array and not an ArrayList thus add them by specifying the index
for (i = 0; i < 2; i++)
{
patients[i] = p;
}
EDIT
If you really want to assign the same object in the string you can even skip the object reference, like
public static void main(String[] args) throws IOException
{
Patient [] patients = new Patient[2];
int i = 0;
for (i = 0; i < 2; i++)
{
patients[i] = new Patient(null, null, 0); // No need for p now
}
}
First you need to initialize an array to be of a specific size.
Patient [] patients = new Patient[2];
Secondly, you need to use index when assigning a value.
patients[i] = p;
Finally;
public static void main(String[] args) throws IOException
{
Patient [] patients = new Patient[2];
for (int i = 0; i < patients.length; i++)
{
patients[i] = new Patient(null, null, 0);
}
}
First:
Some fixes:
class Patient
{
public String patientNo;
public String patientName;
public int procedureType;
public Patient(String ptNo, String ptName, int procType)
{
this.patientNo = ptNo;
this.patientName = ptName;
this.procedureType = procType;
}
}
Since you want your patients to be unique not the same as Patient.sth is class' property (common to all instances).
Now array and inserting:
Patient patients[] = new Patient[2];
for (int i = 0; i < patients.length; i++)
{
patients[i] = new Patient(null, null, 0);
}
but again do not fill array with the same objects. In addition not to be bound to fixed array size - use Vector (for example)
Update: about class members / aka static object members
These 2 code samples are completely different things:
class X
{
public String abc;
public void someMember()
{
this.abc = ;
}
}
and
class X
{
public static String abc;
public void someMember()
{
X.abc =
}
}
You must distinguish between what is unique to an abject and what is common to a class (ie available to all instances - common to them).
With static keyword you declare class members (they will be common foa all instances). You cannot use them with 'this' keyword which is reserved for instance members from the first example.
Here is what you must read class vs instance members

Java - Is it possible to instance for a UserDefined Class or java primitive types

I have a user defined class like the following,
package com.hexgen.tools;
public class UserDefinedParams {
private String dataType="";
private String isArray="";
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public String getIsArray() {
return isArray;
}
public void setIsArray(String isArray) {
this.isArray = isArray;
}
}
dataType and isArray the values for this if dataType -> this may have userdefined pojo class or java primitive type and if isArray ->this will have Y or N. based on this how to create something like:
if dataType someUserDefinedPOJO and isArray Y
-> someUserDefinedPOJO[] obj = new someUserDefinedPOJO();
vise versa for java primitive types too.
is it possible through reflection in java?
How to do this?
Best Regards
just use a HashMap<String,Object> ,
you can define all your variables in there, for example:
HashMap<String,Object> map=new HashMap<String,Object>();
map.put("myVarName",new Object());
System.out.printlb(map.get("myVarName"));
There are no dynamic variables in Java. Java variables have to be declared in the source code.
Depending on what you are trying to achieve, you should use an array, a List or a Map; e.g.
See here.
int n[] = new int[3];
for (int i = 0; i < 3; i++) {
n[i] = 5;
}
List<Integer> n = new ArrayList<Integer>();
for (int i = 1; i < 4; i++) {
n.add(5);
}
Map<String, Integer> n = new HashMap<String, Integer>();
for (int i = 1; i < 4; i++) {
n.put("n" + i, 5);
}
I think you should look into java reflection. But this has already posted on SO.
Read link 1
Read link 2
Another possible route is to go with generics:
public class CustomVariable<E> {
private E var;
public CustomVariable<E>(E value){
var = value;
}
}
But I wouldn't know about arrays though.

Init array of object and pass values

I know there are plenty of question like this in the forum, but after searching for a good while I havent found the answer. I'm also very new to programming so dont flame me please.
I want to creat 8 objects off my class and pass different values to them.
f.e.
public class exampleClass(){
int value;
}
and then init them:
for(int i=0; i<7; i++){
exampleClass c= new // I get lost at this point
//and how can we pass "i" to the var "value" inside the new objects?
}
thanks a lot!
You need to give ExampleClass a constructor to populate the value. For example:
public class ExampleClass {
private final int counter;
public ExampleClass(int counter) {
this.counter = counter;
}
}
...
ExampleClass[] array = new ExampleClass[7];
for (int i = 0; i < array.length; i++) {
array[i] = new ExampleClass(i);
}

Categories

Resources