Array of arrays -- JAVA - java

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");
}

Related

Java: creating several instances of object in class itself or how to restructure

I'm a java beginner and have a question concerning how to best structure a cooking program.
I have a class called Ingredient, this class currently looks like this:
public class Ingredient {
private String identifier;
private double ingredientFactor;
private String titleInterface;
public Ingredient(String identifier, double ingredientFactor,String titleInterface) {
this.identifier = identifier;
this.ingredientFactor = ingredientFactor;
this.titleInterface = titleInterface;
}
I want to initialize several objects (about 40) with certain values as instance variables and save them in a Map, for example
Map<String, Ingredient> allIngredients = new HashMap<String, Ingredient>();
allIngredients.put("Almonds (ground)", new Ingredient("Almonds (ground)", 0.7185, "Almonds (ground)");
Later on I want to retrieve all these objects in the form of a Map/HashMap in a different class.
I'm not sure how to proceed best, initialize all these objects in the Ingredient class itself or provide a method that initializes it or would it be better to create an super class (AllIngredients or something like that?) that has a Map with Ingredients as instance variables?
Happy for any suggestions, thanks in advance :)
Please do not initialize all these objects in the Ingredient class itself. That would be a bad practice for oops.
Just think your class is a template from which you create copies(objects) with different values for attributes. In real world if your class represent model for a toy plane which you would use to create multiple toy planes but each bearing different name and color then think how such a system would be designed. You will have a model(class). Then a system(another class) for getting required color and name from different selection of colors and names present(like in database,files,property file ) etc.
Regarding your situation .
If predetermined values store the values in a text file,properties file,database,constants in class etc depending on the sensitivity of the data.
Create Ingredient class with constructors
Create a class which will have methods to initialize Ingredient class using predetermined values,update the values if required,save the values to text file -database etc and in your case return as map .
Also check the links below
http://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm
http://www.oracle.com/technetwork/java/dataaccessobject-138824.html
Sounds to me like you are looking for a static Map.
public class Ingredient {
private String identifier;
private double ingredientFactor;
private String titleInterface;
public Ingredient(String identifier, double ingredientFactor, String titleInterface) {
this.identifier = identifier;
this.ingredientFactor = ingredientFactor;
this.titleInterface = titleInterface;
}
static Map<String, Ingredient> allIngredients = new HashMap<String, Ingredient>();
static {
// Build my main set.
allIngredients.put("Almonds (ground)", new Ingredient("Almonds (ground)", 0.7185, "Almonds (ground)"));
}
}

Java : How to store Integer and String in array and retrieve values in another class? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a model: fase.java with Integers and Strings + getters and setters:
public class Fase implements Serializable {
private Integer age;
private String name;
}
I want to store both the Integer and String in a Array or ArrayList. I now use this:
public String[] getAllValues(){
String[] values = {age.toString(), name};
return values;
Then in dataServiceImpl.java I retrieve the data with:
user.getFase().getAllValues()[0];
and retrieve the age.
This works, but I have a lot more than age and name, and was thinking if I could put everything in Fase.java in one Array/ArrayList, because they are Integer and String, and then retrieve it in dataServiceImpl.java?
Something like this in Fase.java: ArrayList <Objects> f3Values = new ArrayList <Objects>();
or Fase [] f3Array = new Fase[34];
and then retrieve that in dataServiceImpl.java with: ArrayList<Fase3.Fase3Array> f3List = new ArrayList<Fase3.Fase3Array>();
and use something like: user.f3List[0]; ?
First, you should learn how Java works.
Is Java "pass-by-reference" or "pass-by-value"?
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Then, you should learn how to properly create an encapsulated class, by defining both constructor(s) and getters, methods, setters (if needed; note that setters in general break encapsulation) etc.
Then, you should understand that to aggregate data you:
create a class, i.e. definition object that holds all the necessary fields,
create a storage aggregate (array, ArrayList, Map, whatever),
3a. create an object of a given class, setting the values of the fields,
3b. add the object to the aggregate,
3c. goto 3a until the aggregate is filled with the data needed.
Explaining that on the code provided, you should first have
public class Fase implements Serializable {
private int age;
private String name;
public Fase( int age, String name ) {
this.age = age;
this.name = name;
}
public int getAge() { return age; }
public String getName() { return name; }
}
then you can create the aggregate, e.g.
int FASE_MAX = 34;
Fase[] fArray = new Fase[FASE_MAX];
ArrayList<Fase> fArrayList = new ArrayList<Fase>(FASE_MAX);
then you create the objects and add them to the aggregate, e.g.
for( int i = 0; i < FASE_MAX; i++ ) {
Fase newFase = new Fase( i, "John Doe" );
fArrayList.add( newFase );
fArray[i] = newFase;
}
then, and only then, you can access the aggregate:
Fase someFase = fArrayList.get( n );
Fase someOtherFase = fArray[n];
Your Fase class can have whatever members and however many members you like and you can access them all. If you want an array of Fase then create one and each element of the array will contain all the Fase members.
Fase[] myArray = new Fase[34];
You have an array of 34 "Fase's" just add whatever members you want to your Fase class.

Fill an Array with different data types

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.

Is there a fixed length generic array object in Java?

I'm looking for a way to store different data types in one fixed length collection so I can set/get elements by index. What's the best way to go about this?
Thanks!
EDIT:
Should this work?
private List t=new ArrayList();
t.set(2,"test");
I get this: java.lang.IndexOutOfBoundsException: Index: 2, Size: 0
Should this work?
private List t=new ArrayList();
t.set(2,"test");
No it shouldn't. A List doesn't automagically grow if you call set with a position that is beyond the end of the list. (See the javadoc.)
If you want to do that kind of thing you have to fill the List with null elements first; e.g.
private List t=new ArrayList();
for (int i = 0; i < LIMIT; i++) {
t.add(null);
}
...
t.set(2,"test");
But I'd also like to reiterate the point that various other answers have made. You should write a class and do this in a type-safe fashion. Stuffing things into an Object[] or List<Object> ... and hoping that you get the indexes and types right ... gives you fragile code. It is bad practice.
You need a Javabean. Create a class which represents the whole picture of all those different properties together. E.g. an User with id, name, gender, dateOfBirth, active, etc.
public class User {
private Long id;
private String name;
private Gender gender;
private Date dateOfBirth;
private Boolean active;
// Add/generate c'tor(s)/getters/setters/equals and other boilerplate.
}
This way you end up with a clear and reuseable abstraction.
User user = new User();
user.setName("John Doe");
user.setGender(Gender.MALE);
// ...
See also:
What is a Javabean?
You can do such a thing with List. It has get/set methods by index. I don't see why fixed length is important here.
You can always encapsulate precisely the behavior you want in a class of your own devising. You can have a backing array to manage it for you, but you'll have to do all the work yourself.
Can't you make an array of Objects? Which means everything except the primitive types (int, char, boolean, etc.); if you want to store them you have to wrap them in their corresponding Object Wrapper classes (Integer, Character, Boolean, etc.) So like:
mult_type[0] = "A String";
mult_type[1] = new Integer(42);
mult_type[2] = new Long(7149994000);
and so on. Although mult_type[i] is an Object by definition, the entry
stored there can be any subclass of Object. When you want to retrieve them,
you can examine them to find out what class they actually belong to. There
are a couple of ways to do this, one is to use the "instanceof" operator
like so:
if (mult_type[i] instanceof Integer) {
Integer anInteger = (Integer)mult_type[i];
int anInt = anInteger.intValue();
}
Notice that you have to "cast" the object to its actual class as you
retrieve it.

What is the datatype of a Java varargs (...) parameter?

I am trying to add information from main()
to a items class where i am storing the information in a hashset
i have 3 classes
project - main()
libaray - addBandMembers function
Item - addband(String... member)
i am adding CD information. first, i add band, # of songs, title - which works good
then in another function i am trying to add the band members. I want to keep these separate.
Where i am having problems is assign the band members..
I understand that how Varargs works just not sure how to assign that to a string..
I will only show bits of code to keep this post simple and short..
this is what i have:
Main()
item = library.addMusicCD("Don't Let Go", "Jerry Garcia Band", 15, "acid rock", "jam bands");
if (item != null) {
library.addBandMembers(item, "Jerry Garcia", "Keith Godcheaux");
library.printItem(out, item);
}
Then, here the first function thats called..
public void addBandMembers(Item musicCD, String... members)
{
//musicCD.addband(members); // both cant find addband function..
//Item.addband(members);
}
Then in another class i am trying to add the information..
private String members;
public void addband(String... member)
{
this.members = member; // error
}
if i make the private String members; an array
then this function below errors.. incompatible type..
public String getMembers()
{
return members;
}
How can i do this?
oh ya, here is my set..
public class Library
{
private Set<CD> theCDs = new HashSet<CD>();
private Set<DVD> theDVDs = new HashSet<DVD>();
private Set<Book> theBooks = new HashSet<Book>();
if you need to see more code let me know..
Thank you so much..
A varargs argument resolves to an array.
So, change
private String members;
to
private String[] members;
Change your getter to return a String array instead of a String.
String... member gives you an array, so what you are looking at is a member that is of type String[].
I think once you get that, you kind of get over the hump of the issue.

Categories

Resources