creating objects with multiple arrays - java

is there an easier way to set multiple lines of a file into an object without typing them all out
Ive got a json array which has parsed a file into an array
i have set each element to a variable
id = array[0];
name = array[1];
position = array[2];
and put it in a for loop where it inputs it into an object class i have created.
for (int ii = 0; ii < array.length(); ii++)
{
Employee [] employee {new Employees (id, name, position)};
}
i tried to print out the object class however it just stored each into its own separe object instead of one big one
the only way ive figure is to do
Employee[] employee = {
new Employee(1210, "Bob", ceo),
new Employee(2210, "Tom", manager),
new Employee(3210, "Terry", teacher),
new Employee(40211 "Joe", student)
};
however my file code is 1000+ lines and i can't afford to be entering it all in, is there a quicker way to do this or a trick with the for loops im missing
ALSO
im trying to call my toString method from my object class and ive done System.out.println(employee.toString()) however it prints out: Before sorting => [Employee;#a09ee92 After sorting => [Employee;#a09ee92 the address memory instead of the actual values, Arrays.toString does work although i cannot use ADT's
thank you

I think you meant to do this but you need to get all the information into separate arrays (or use the a JSON parser as recommended in the comments). presumes the source arrays are all the same length.
Employee[] employees = new Employee[id.length];
for (int ii = 0; ii < array.length(); ii++) {
// if you don't have all the information in three arrays
// and you need to create each array of three items as you read
// the file you could do that here.
employees [ii] = new Employee(id[ii], name[ii], position[ii])};
}
Then to print them you can do this.
System.out.println(Arrays.toString(employees));
Or iterate thru the list with a for loop. Note that for the output to be meaningful you need to override the toString() method in you Employee class.

Related

Creating an Array made from ArrayLists

In a given homework problem I'm supposed to create a matrix/or two-dimensional array of 2x9 dimensions in which each element contains an arraylist of objects of "Patient" type.
Patient is an object created from the class Patients.
Is that even possible? How do I even declare such a thing?
I tried:
<ArrayList>Patients[][] myArray = new ArrayList<Patients>[2][9];
but it didn't work. I'm not really sure how to even make an array[][] of ArrayList-objects.
EDIT
With everyone's help I have now initialized the bidimensional-Arraylist as:
ArrayList<Patients>[][] patientsMatrix = new ArrayList[2][9];
But I'm now kind of stuck at how to enter each element, I tried with this format:
patientsMatrix[0][j].add(myPatientsList.get(i));
I'm getting a java.lang.NullPointerException at the first item it reads, I thought that by declaring the matrix with "new ArrayList[2][9]" at the end it wouldn't throw this kind of exception?
myPatientsList is a patient-type arraylist, could it be what is causing trouble here?
ArrayList<Patients>[][] myArray = new ArrayList<Patients>[2][9];
You can also have an ArrayList of ArrayList of ArrayList<Patients>.
Something like ArrayList<ArrayList<ArrayList<Patient>>> patientArray = new ArrayList<>(2)
And then you initialize each of the inner ones like:
for (int i = 0; i < 2; i++) {
patientArray.add(new ArrayList<ArrayList<Patient>>(9));
}
It's essentially a 2-D matrix of dimensions 2x9 of ArrayList<Patients>

Dynamically adding Strings to an object[]

I'm working on a project for work involving a JTable with a dynamic number of columns. Each column is basically a separate transaction but I do not know the number of transactions a file will have ahead of time.
Typically when I create a JTable I know how many columns I will have and I declare it like this:
String header[] = new String[]{
"Tag","Transaction1"
};
For this project however there can be any number of transactions each time the program is used so I would need to dynamically add columns based upon the length of a certain array before I even create my rows. (The first row is actually going to also be used as a header).
So I have an array with a given length, but I don't know how to use this value in a loop, at least not with creating an object like the code above shows.
For example let's say the user uploads a file that has 3 transactions.. I would need my String header[] to read:
String header[] = new String[]{
"Tag","Transaction1","Transaction2","Transaction3"
};
I'd considered possibly creating an array list and adding the transactions to this using a counter and a loop, then possibly extracting the values into the String[] header although I'm not sure if this is the best approach and even still how exactly to make it work.
I actually found the answer to this.. Apparently I need to scrap the entire array and add them like this..
DefaultTableModel tableModel = new DefaultTableModel();
for(String columnName : columnNames){
tableModel.addColumn(columnName);
}
jTable.setModel(tableModel);
A good option for you would be to have an ArrayList to dynamically add or remove elements from the List.
Then, when necessary, you can turn that ArrayList into an array of Strings, like..
ArrayList<String> elements = new ArrayList<String>();
elements.add("Transaction 1");
elements.add("Transaction 2");
elements.add("Transaction 3");
Object[] elementArray = elements.toArray();
I thing you dont need to use an Array, use better an List, this because you can increase the size as much as you need, iterate it, parse it to string-Arrays etc.
Example
List<String> transactions = new ArrayList<String>();
transactions.add("Tag");
// later
transactions.add("Transaction1");
transactions.add("Transaction2");
// print it
for (final String string : transactions) {
System.out.println(string);
}
List<String> headerList = new ArrayList<>();
headerList.add("Tag");
for(int i=1; i <= transactions.length; i++){
headerList.add("Transaction" + i);
}
String[] header = headerList.toArray(new String[headerList.size()]);
I believe what you're looking for is an ArrayList, not an Array nor List, as this allows for dynamic allocation.
The syntax would be:
List<String> header = new ArrayList<String>();
header.add("Tag");
That initializes it. Then, use length() from your File class to set a parameter for a loop, then dynamically add the result of string concatenation with the "Transaction" + your loop index to your ArrayList.
That'd look like:
for (int i = 1; i <= file.length(); i++){
header.Add("Transaction" + i);
}
And, then you can convert it back to an array of strings with:
String[] headerArray = header.toArray(new String[header.size()]);

Adding value to java array in the right place

I am trying to write a little program that will contain a array of profiles of people and I am stuck on the method for adding the profiles, as I would like them to be added in correct place so it doesn't need to be sorted. For example
If I have a array with 3 profiles
Potter, H
Smith, T
Warren, B
And I want to add Summer, P I would like it to be added right between the 1st and 2nd index
Before anyone asks I haven't got much code for this as I am still thinking on how to search the array and say where the profile needs to be placed.
Any ideas are appreciated
(Also it needs to be a Array not a ArrayList or any other data structure)
If you want to use an array rather than a decent, appropriate data structure, then use Arrays.binarySearch() to find the appropriate location. But you'll have to shift all the subsequent elements.
Whatever you are talking about is best done by the LinkedList http://docs.oracle.com/javase/6/docs/api/java/util/LinkedList.html
Since you want to use Array only, then as you know arrays have a constant number of elements that you declare. So I recommend you to create a temporary ArrayList and then copy those elements into an array that you want. Here how it's done
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
String[] yourInitialArray = { "Potter, H", "Smith, T", "Warren, B" };
// Creating a temporary ArrayList
ArrayList<String> temporary = new ArrayList<String>();
for (int i = 0; i < yourInitialArray.length; i++) {
if (i != 1) {
temporary.add(yourInitialArray[i]);
} else {
temporary.add("Summer, P");
temporary.add(yourInitialArray[i]);
}
}
yourInitialArray = new String[temporary.size()];
for (int j = 0; j < temporary.size(); j++) {
yourInitialArray[j] = temporary.get(j);
System.out.println(yourInitialArray[j]);
}
}
}
try to adding normally after that sort the list.It is better to use
First of all, I would highly recommend using the Collections framework List over the Arrays. because it provides the lot of flexibility and improvements over using normal arrays
and for your solution, i would recommend using the LinkedList. This provides the method add(int index, E element ) for inserting the element at specific location and it is very efficient

concatenate fields from array of Java objects

I am a newbie to Java. I have an array of objects that have a string field. I can concatenate all of the strings into an string array by looping, but it's very inelegant.
int numObj = obj.length;
String[] strArray = new String[numObj];
for (int i = 0; i < numObj; i++) {
strArray[i] = obj[i].strField;
}
Is there a way to concatenate that single field from all of the objects into a string array in one command? e.g.:
String[] strArray = (String[]){obj[].strField};
This doesn't work because obj[] is an array and so it doesn't have any fields, but using {obj.strField} doesn't work either, because there is no object called obj. BTW I really don't have to recast the field or do .toString() because it is already a string.
I looked at many, many of the other posts (but perhaps not enough?) related to this but I still could not figure this out. There are some that refer to converting an object array to a string array, but I don't think those posts mean converting a particular field in the objects, but the object itself, as an uncast type.
In MATLAB this would be trivial: strCellArray = {obj.strField}; would create a cell array of strings from all of the strFields in obj instantly.
Thanks for your help.
What you did is the only way. You don't have to create a variable for the length of the array, though. And using public fields is, 99.99% of the times, a very bad idea:
String[] strings = new String[objects.length];
for (int i = 0; i < objects.length; i++) {
strings[i] = objects[i].getStringField();
}

How do I dynamically name objects in Java?

Let's say I needed to make a series of String[] objects.
I know that if i wanted to make a string array called "test" to hold 3 Strings I could do
String[] test = new String[3];
But let's say I needed to make a series of these arrays and I wanted them to be named, 1,2, 3, 4, 5... etc. For however many I needed and I didn't know how many I'd need.
How do I achieve a similar effect to this:
for (int k=0; k=5; k++){
String[] k = new String[3];
}
Which would created 5 string arrays named 1 through 5. Basically I want to be able to create array objects with a name detemined by some other function. Why can't I seem to do this? Am I just being stupid?
There aren't any "variable variables" (that is variables with variable names) in Java, but you can create Maps or Arrays to deal with your particular issue. When you encounter an issue that makes you think "I need my variables to change names dynamically" you should try and think "associative array". In Java, you get associative arrays using Maps.
That is, you can keep a List of your arrays, something like:
List<String[]> kList = new ArrayList<String[]>();
for(int k = 0; k < 5; k++){
kList.add(new String[3]);
}
Or perhaps a little closer to what you're after, you can use a Map:
Map<Integer,String[]> kMap = new HashMap<Integer,String[]>();
for(int k = 0; k < 5; k++){
kMap.put(k, new String[3]);
}
// access using kMap.get(0) etc..
Others have already provided great answers, but just to cover all bases, Java does have array of arrays.
String[][] k = new String[5][3];
k[2][1] = "Hi!";
Now you don't have 5 variables named k1, k2, k3, k4, k5, each being a String[3]...
...but you do have an array of String[], k[0], k[1], k[2], k[3], k[4], each being a String[3].
The closest you will get in Java is:
Map<String, String[]> map = new HashMap<String, String[]>();
for (int k=0; k=5; k++){
map.put(Integer.toString(k), new String[3]);
}
// now map.get("3") will get the string array named "3".
Note that "3" is not a variable, but in conjunction with the map object it works like one ... sort of.
What you want to do is called metaprogramming - programming a program, which Java does not support (it allows metadata only through annotations). However, for such an easy use case, you can create a method which will take an int and return the string array you wanted, e.g. by acccessing the array of arrays. If you wanted some more complex naming convention, consider swtich statement for few values and map for more values. For fixed number of values with custom names define an Enum, which can be passed as an argument.

Categories

Resources