I have a Class named Group, it is described as follow:
public class Group{
public int identifier;
public int[] members;
public String name;
}
Now, I would like to create many different objects for this class, I mean for example 1000 groups each one has different number of members,
How can make it? I mean I would not make 1000 instructions like:
Group g1= new Group(....);
Thanks and best regards.
You need to research arrays, and loops:
Group[] groups = new Group[1000];
for (int i = 0; i < 1000; i++) {
groups[i] = new Group();
groups[i].identifier = XXX;
groups[i].members = new int[XXX];
...
}
Can you not use an array and a loop? E.g.:
...
public static final int ARRAY_SIZE = 1000;
...
Group arr[] = new Group[ARRAY_SIZE];
for( int i = 0; i < arr.size; i++ ) {
arr[i] = new Group();
}
If you want to assign different values to each of the 100 instances, then yes, you are facing a lot of typing. You can create the objects in a loop ( as Oli describes ), but to assign the different values you'll still end up doing
groups[0].identifier = 10;
groups[1].identifier = 44;
groups[3].identifier = 99;
etc etc.
You may be able to put the parameters in a file and wirte code to read the file and set the values in your object instances, but one way or another, unless the parameters can be generated by algorithm, you're going to end up typing them in
Related
I am working on a project which I am asked to make a database for a company that has 3 different types of employees, Programmer/Student Programmer/QATester, I have make for each one of those an array of it's type, because each one has it's own specific notes, The problem is,I am asked that if someone would search an employee through ID number and gets his name, I need to search through all of them, so I though about making an Array of Arrays, which has those 3 arrays.
But here is what happens:
public class EmployeesDB {
private String companyName;
private int programmers;
private int studentProgrammers;
private int QATesters;
public Programmer[] ProgrammersArray;
public StudentProgrammer[] StudentsArray;
public QATester[] QATArray;
public String[][] KO ;
public EmployeesDB(String name, int numOfProgrammers, int numOfStudents, int numOfTesters) {
this.companyName = name;
this.programmers = numOfProgrammers;
this.studentProgrammers = numOfStudents;
this.QATesters = numOfTesters;
StudentsArray = new StudentProgrammer[numOfStudents];
ProgrammersArray = new Programmer[numOfProgrammers];
QATArray = new QATester[numOfTesters];
KO = new String[][]{StudentsArray,ProgrammersArray,QATArray};
}
and it keeps showing :
- Type mismatch: cannot convert from StudentProgrammer[] to String[]
- Type mismatch: cannot convert from Programmer[] to String[]
- Type mismatch: cannot convert from QATester[] to String[]
I am new, and I am not able to find a solution.
Please help me.
thank you!
You are trying to convert 3 Arrays of different Classes to String Arrays
KO = new String[][]{StudentsArray,ProgrammersArray,QATArray};
You will have to do that into a Object[][], and then use instance of whenever you need
public Object[][] KO ;
//...
KO = new Object[][]{StudentsArray,ProgrammersArray,QATArray};
if (KO[0][0] instanceof Programmer) {...}
In this situation, the Polymorphic nature of Java Objects can be exploited for our advantage.
NOTE: any 1 of these 2 soltion cases can be utilised to get the desired results.
Assuming you DON'T WANT the classes Programmer, StudentProgrammer and QATester to be subclasses of String, you can proceed as:
Instead of declaring KO as:
public String[][] KO ;
you can declare KO as:
public Employee[][] KO;
where Employee is the super class of classes Programmer, StudentProgrammer and QATester.
Assuming you WANT the classes Programmer, StudentProgrammer and QATester to be subclasses of String, you can simply make these 3 classes extend the class String.
Now, to access an element of the array KO, and to convert it back to its abstract form, you can simply proceed as:
if(KO[x][y] instanceof Programmer){
Programmer employeeAtXandY = (Programmer) KO[x][y];
System.out.println("Employee Element at x and y is a Programmer");
}
i need to fill an Array with different data types
InvoiceItem[] invoiceItems;
int test = 3;
int i = 0;
This needs to be in the Array:
InvoiceItem invoiceItem = new InvoiceItem();
invoiceItem.setItemType("TestItem");
invoiceItem.setArticleNo("TestItemID");
invoiceItem.setDescription("TestDescription");
invoiceItem.setQty(1);
invoiceItem.setPrice(new BigDecimal(20.00));
invoiceItem.setVat(new BigDecimal(5.0));
There is the possibility that there is more than one InvoiceItem (test=3), so it needs to be in a loop.
It has to be an Array, i need to pass it to another class which only accepts an Arrays.
How can i achieve this?
Edit: I will try to make my question more clear:
I need to know how to put these
invoiceItem.setItemType("TestItem");
invoiceItem.setArticleNo("TestItemID");
invoiceItem.setDescription("TestDescription");
invoiceItem.setQty(1);
invoiceItem.setPrice(new BigDecimal(20.00));
invoiceItem.setVat(new BigDecimal(5.0));
in an Array:
int countofInvoiceItem = 3; // there are 3 InvoiceItem
InvoiceItem[] invoiceItems = new InvoiceItem[countofInvoiceItem];
Where there can be more than one InvoiceItem.
Method looks like this:
public final ResponseCreateInvoice CreateInvoice
(Invoice Invoice, InvoiceItem[] InvoiceItems, Address DeliveryAddress, Address InvoiceAddress, String UserID, String Password)
(This is given and i can not change)
and returns
ResponseCreateInvoice inv = wsClient.createInvoice(invoice, invoiceItems, deliveryAddress, invoiceAddress, userID, password);
i am sort of new to Java (or arrays), so this may be an easy question, but i don't really get it. Also does it matter that there are Strings and Int, BigDecimal etc mixed together in an Array?
You just need to declare your array as an array of type T where T is a superclass of all the classes of the objects you want to fill it with. In the worst case, it would be Object but it's bad design 9 times out of 10.
I would recommend you to make a class that holds everything you need as follows:
public class YourClass{
int id;
double value;
String description;
//and so on
//create getters and setters
}
And you can use this class to pass array of objects to another class.
Put your objects of the class in the Array
For example
YourClass[] objects = new YourClass[SIZE];//define number of objects you need
And you can pass each and every objects separately or as a whole to another class.
And in your receiving class, you can have a constructor as:
public YourRecievingClass(YourClass[] object){
//and recieve here as you need; ask further if you need help here too
}
I think this is the best way to adopt though your question is not 100% clear
Based on your edit, your original question is off base. You do not want to create an array of different types but instead only want to create an array of one type and one type only, that being an array of InvoiceItems. You are confusing object properties with array items, and they are not one and the same. This code here:
invoiceItem.setItemType("TestItem");
invoiceItem.setArticleNo("TestItemID");
invoiceItem.setDescription("TestDescription");
invoiceItem.setQty(1);
invoiceItem.setPrice(new BigDecimal(20.00));
invoiceItem.setVat(new BigDecimal(5.0));
is where you are changing the properties of a single InvoiceItem.
It seems that your InvoiceItem class has String fields for item type, for article number, for description, an int field for quantity, a BigDecimal field for price and a BigDecimal field for VAT. And so your array would look simply like:
InvoiceItem[] invoiceItems = new InvoiceItem[ITEM_COUNT]; // where ITEM_COUNT is 3
You could use a for loop to then create your items:
for (int i = 0; i < invoiceItems.length; i++) {
invoiceItems[i] = new InvoiceItem();
}
And you could perhaps use the same for loop to fill in the properties of each InvoiceItem in the array:
for (int i = 0; i < invoiceItems.length; i++) {
invoiceItems[i] = new InvoiceItem();
invoiceItems[i].setItemType(???);
invoiceItems[i].setArticleNo(???);
invoiceItems[i].setDescription(???);
invoiceItems[i].setQty(???);
invoiceItems[i].setPrice(???);
invoiceItems[i].setVat(???);
}
But the unanswered question is, ... where do you get the data for each property of each InvoiceItem in the array? Is this information contained in a file? Is it inputted by the user? That is something you still need to tell us.
With which types of data? In general, you could use:
Object[] myArray;
All classes are subclasses of Object.
I'd like to write a program which creates a set of objects in a loop....
(i.e.)
String newFirm = "empty";
for(int i=0; i<30; i++)
{
newFirm = "firm" + i;
firm newFirm = new firm();
}
and then of course I would need something like
stringToObject = "firm" + x;
stringToObject.type = "service";
stringToObject.size = 10000;
Obviously this code is fictional, but It expresses how I'd ideally create and call for objects. The nature of this program is such that the final number of firms (or other objects) are not known at the time of compiling.
Is there a method by which I can convert a given string into the name of an object (either to call or to create) as well as creating objects "on the fly"?
Sounds like a job for an ArrayList.
ArrayList<Firm> myList = new ArrayList<Firm>();
And in your loop,
Firm firm = new Firm();
firm.type = "service";
myList.add(firm);
And to get it,
Firm f = myList.get(index);
convert a given string into the name of an object
Your need is to refer an object with the string in your hand. I'll suggest Hashmap<String,Object>
Eg:- you have a String,
String name="object_name";
And your class is Firm. Now,
Hashmap<String,Firm> objs=new Hashmap<String,Firm>();// note:your for loop comes after this line
Firm new_firm=new Firm();
new_firm.type = "service";
new_firm.size = 10000;
objs.put(name,new_firm);
Now you can refer your object with the string in your hand as
objs.get("object_name");
I am studying data object in Java
I have question for creating the data object dynamically.
For example ,
we have...
public class tasks {
private int vmnumber;
private int tasknumber;
private String status;
public tasks(int vmnumber , int tasknumber , String status) {
this.vmnumber = vmnumber;
this.tasknumber = tasknumber;
this.status = status; }
and there are some getvmnumber gettasknumber , getstatus , and some set functions for
what I understand about creating data object is we have to initialize each time.
for example , in the main file ,
public class task{
public static void main(String [] args){
task t = null , t2 = null;
t = new task();
t.tasknumber = 3;
t.vmnumber = 4;
t.status = "Start";
t2 = new task();
t.tasknumber = 2;
t.vmnumber = 1;
t.status = "Wait";
}
however, i would like to how we can create data object dynamically because program possibly get the information of tasks on real time.(then we can't manually create the data object, we need to something which can create the data object dynamically...)
Second, I would like to know how to get the data from data object.
For example , if we want to find all the information of task number 3 , what should i do ?
lets say , we have task1, task2, task3 data object and we want to see the all information of task1. then what should i do ?
thanks
There are few points to discuss, from your question.
I guess you want to create new tasks, which is maybe a request from the user interace of your application, or a webservice, a batch...
Well, you already know how to create object : with the new keyword. Depending on the original request, your main function may have to create multiple instances of the same class, "Task".
More, when you instantiate the class "Task", you would never want to assign directly values to the properties of it.
So, instead of coding t.tasknumber = 3, you should code : t.setTaskNumber(3)
Also, you should rename the properties of your class to reflect the JavaBeans conventions :
- private int taskNumber instead of tasknumber
Of course, it is only a convention, and it is not mandatory in your program. But it helps generating getters/setters, and, well, it is a convention :-)
To retrieve "information" within your created tasks, you only have to call the getters :
- myTask.getTaskNumber()
Hope this helps you a little bit.
How to generate unique ID that is integer in java that not guess next number?
How unique does it need to be?
If it's only unique within a process, then you can use an AtomicInteger and call incrementAndGet() each time you need a new value.
int uniqueId = 0;
int getUniqueId()
{
return uniqueId++;
}
Add synchronized if you want it to be thread safe.
import java.util.UUID;
public class IdGenerator {
public static int generateUniqueId() {
UUID idOne = UUID.randomUUID();
String str=""+idOne;
int uid=str.hashCode();
String filterStr=""+uid;
str=filterStr.replaceAll("-", "");
return Integer.parseInt(str);
}
// XXX: replace with java.util.UUID
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(generateUniqueId());
//generateUniqueId();
}
}
}
Hope this helps you.
It's easy if you are somewhat constrained.
If you have one thread, you just use uniqueID++; Be sure to store the current uniqueID when you exit.
If you have multiple threads, a common synchronized generateUniqueID method works (Implemented the same as above).
The problem is when you have many CPUs--either in a cluster or some distributed setup like a peer-to-peer game.
In that case, you can generally combine two parts to form a single number. For instance, each process that generates a unique ID can have it's own 2-byte ID number assigned and then combine it with a uniqueID++. Something like:
return (myID << 16) & uniqueID++
It can be tricky distributing the "myID" portion, but there are some ways. You can just grab one out of a centralized database, request a unique ID from a centralized server, ...
If you had a Long instead of an Int, one of the common tricks is to take the device id (UUID) of ETH0, that's guaranteed to be unique to a server--then just add on a serial number.
If you really meant integer rather than int:
Integer id = new Integer(42); // will not == any other Integer
If you want something visible outside a JVM to other processes or to the user, persistent, or a host of other considerations, then there are other approaches, but without context you are probably better off using using the built-in uniqueness of object identity within your system.
Just generate ID and check whether it is already present or not in your list of generated IDs.
UUID class
Do you need it to be;
unique between two JVMs running at
the same time.
unique even if the JVM
is restarted.
thread-safe.
support null? if not, use int or long.
if only int is required then AtomicInteger can make it possible.
if String is needed then the below code should work by mixing timeStamp and
AtomicLong.
AtomicLong idCounter = new AtomicLong(100);
long timestamp = System.currentTimeMillis();
long nextLong = idCounter.incrementAndGet();
String randomId = String.valueOf(timestamp)+String.valueOf(nextLong);
Imagine you have a class called employee with these attributes:
public class Employee {
private final String name;
private int id;
private static int nextID = 1;
public Employee(String name) {
this.name= name;
id = nextID++;
}
}
Easy peasy
Unique at any time:
int uniqueId = (int) (System.currentTimeMillis() & 0xfffffff);