How do I dynamically name objects in Java? - 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.

Related

creating objects with multiple arrays

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.

I never figure out the correct way to create an 2D ArrayList

List<ArrayList<Planet>> NAME = new ArrayList<ArrayList<Planet>>(N);
List<List<Planet>> NAME = new ArrayList<ArrayList<Planet>>(N);
ArrayList<ArrayList<Planet>> NAME = new ArrayList<ArrayList<Planet>>(N);
I can't tell what's the difference of these three expressions. I realized later that maybe List is for declaration because its an interface while ArrayList could be used for initiation, as it is a class. I took the first syntax in my project and find
found : java.util.ArrayList>
required: java.util.ArrayList>
List<List<Planet>> Name = new ArrayList<ArrayList<Planet>>(N);
I have added at the header.
import java.util.ArrayList;
import java.util.List;
In another place, while I am adding Planet Object into the ArrayList:
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (i == j) continue;
NAME[i].add(planets[j]);
}
}
The compiler reports,
array required, but java.util.ArrayList> found
planetsForNetForceSetting[i].add(planets[j]);
Could anybody tell me the reason for this?
You are trying to retrieve data from given position of a List like an Array here: NAME[i].add(planets[j]);, what cannot be done.
To get data from an ArrayList you must use get(int) method. In thi way: NAME.get(i) instead NAME[i].
Then, your method must be
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (i == j) continue;
NAME.get(i).add(planets[j]);
}
}
About difference of three expressions, and why use interface to declare List<Object> list = new ArrayList<Object> instead of the class itself, look at this question.
First List<T> is a java interface parametrized by type T. ArrayList<T> is specific implementation of interface List<T>. So you may assign List<Integer> list = new ArrayList<Integer>(); This way variable list will have type List<Integer> which will hide specific implementation ArrayList<T>.
Then following lines:
List<ArrayList<Planet>> planetsList = new ArrayList<ArrayList<Planet>>();
creates variable planetsList of type List<ArrayList<Planet>> which is list of array lists. Where actual outer lists implementation is ArrayList<ArrayList<Planet>>.
List<List<Planet>> planetsList2 = new ArrayList<ArrayList<Planet>>();
Will not compile, since you cannot assign ArrayList<ArrayList<Planet>> to List<List<Planet>> Refer to this question to more deep explanation why Why can't you have a "List<List<String>>" in Java?
ArrayList<ArrayList<Planet>> planetsList3 = new ArrayList<ArrayList<Planet>>();
Will create variable planetsList3 with type ArrayList<ArrayList<Planet>>.
You need to import both java.util.List and java.util.ArrayListtypes since you are directly referencing them in your code.
And finally. You cannot assign item to list's index by array indexing syntax items[index]=item; since List<ItemType> items; is an interface not an array. These are totally different things in java.
Out of your 3 expressions, in same order as you mentioned, 2nd one is the most generic one, then 1st and then 3rd.
Which means that when you use List<Planet> listObj then you can use listObj to point to any implementation of List interface. While when you do ArrayList<Planet> listObj then you can use listObj to point to only an object of type ArrayList
Whether 1 dimensional or N dimensional, this hold true.
A more generic type and preferred one would be use of List<Object> listObj, which means that you can use listObj to point to any implementation of List interface, ALSO you in the list you can put any object. When you use List<Planet> listObj then you can only put Planet objects.
For your compile problem, your code is not sufficient to figure out root cause because I cannot see whats planetsForNetForceSetting, but just make sure that you are putting right objects in right place. Like I explained above.
Hope this helps!!!

Java valuable used as a part of identifier

I have a few rows like:
int a1;
int a2;
int a3;
...
And I want a cycle that uses an other integer to identify the specific 'a'.
For example:
int k;
k gets a random number then I use the a'k' valuable.
That's not possible, but you can create an array like int[] a = new int[20];. Then you can access randomly the elements (from 0 to 19) with a[randVariable] = 4;.
Given the names, you are probably looking for "the array way" (see Kayaman's answer):
int[] a = new int[10];
// ...
for (int i : a) {
// do something with 'i'
}
However, if you cannot declare those objects as an array, you can always create one just in time:
int a, b, c, d, e;
// ...
for (int i : new int[] {a, b, c, d, e}) {
// do something with 'i'
}
If you do not necessarily want to iterate all of them, but just a few:
If they form a contiguous range (no empty spaces), declare them as an array, or build an array with the elements so you can, from then on, index using that array. This is similar to the approach in the above code samples.
If they do not form a contiguous range (large, empty spaces), use a Map (if you need some kind of sorting and consistent ordering, use TreeMap; use HashMap otherwise)
In the second case, you are creating an array and initializing it at the same time, and then iterating its elements.
If you have described this right in that you want to get a variable called
variableName = "a" + anInteger; // e.g. a1, a2, a3
Then you would need to use Java reflection
Field field = yourClass.getClass().getField(variableName);
But you would need to do some sorting of the field based on type. This seems complex for your level of Java though.
You can do this in Java using reflection, assuming that your variables are fields of a class. But I'd advise against this as it makes your code brittle and is probably unnecessary.
Use an array instead if you can: e.g. int[] a = new int[ToDo: size here];
You want to use arrays:
int a[] = new int[10];
int k = ....set a value....
... do something with .... a[k]
You may need reflection, building a String with the field name and then use Reflection API (https://docs.oracle.com/javase/tutorial/reflect/) to search for a field with name a1, a2, ...

Matching of the Parameters in Vectors

I am trying to Learn Java as I am a beginner and recently i fumbled upon Vectors and Lists in Java. This is a very simple and a basic question, but any help would be really helpful for a learner.
I have created a vector v as shown below:
public vector createVector(){
Vector v = new Vector();
v.add(Path1); //Path1 is the path of a directory
v.add(Path2);
return v;
}
I have a function in which I pass, one of the parameter is v.get(i). The function is shown below:
for(int i=0,i<v.size(),i++){
qlm("Write", "init",getList(),**v.get(i)**); // Function call.
}
Function declaration is :
Void qlm(String Option, String init, List lists, **String paths**){
}
I am not able to match the parameter in the function call which is v.get(i) with String Paths. Please share your knowledge.
Thanks a lot.
Without Generics, v.get(i) will always return an object. Here are two ways to resolve it:
Declare Vector as
Vector< String > v = new Vector< String > ();
Or do
v.get(i).toString();
But before doing v.get(i).toString(), null check should be performed on v.get(i).
try this
for(int i=0,i<v.size(),i++){
qlm("Write", "init",getList(),v.get(i).toString()); // Function call.
}
Typically, in Java, when somebody declares a Vector they will declare it using Generics. To declare a Vector that will contain strings, you would write this:
Vector<String> myVector = new Vector<String>();
Then, to get a iterate over it's values, you would do this:
for(int i = 0; i < myVector.size(); i++){
String s = myVector.get(i); // The get() method here returns a String instead of Object
}
Or, because Vectors are enumerable, you could do this:
for(String s : myVector){
// There is now a variable named s available in the loop that
// will contain each element in the vector in turn.
}
That being said, you really shouldn't use Vectors any more. They are pretty old, and there are better lists available in Java. I would recommend that you use an ArrayList, but they're a variety of lists available which can be found here under "All known implementing classes."
To rewrite your example using generics and an ArrayList, you would do this:
List<String> myList = new ArrayList<String>();
myList.add(Path1);
myList.add(Path2);
for(String s : myList){
qlm("Write", "init", getList(), s);
}

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

Categories

Resources