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();
}
Related
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 am trying to cast a 2D Object array column as a 1D String array; I have no problem getting the data itself, but it is the data types which creates a run-time error:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String
cannot be cast to [Ljava.lang.String;
This is an example of the code fragment I am working with:
Object[][] currentData = BackOffice.getData();
String[] dataWanted = null;
for (int i=0; i<currentData.length; i++)
dataWanted = (String[])currentData[i][1];
I thought I could get away with casting using (String[]), but obviously not...
any help appreciated!
If I understand correctly, you want to do:
String[] dataWanted = new String[currentData.length];
for (int i=0; i<currentData.length; i++)
dataWanted[i] = currentData[i][1];
currentData is a 2D array of Objects, so currentData[i][1] evaluates to a single Object. dataWanted is an array of Strings. You can't cast a single Object into an array type. Additionally, arrays must be initialized with a size before inserting items. If you'd like to place each Object into the dataWanted array you'll want something like this:
String[] dataWanted = new String[currentData.length];
for (int i = 0; i < currentData.length; i++) {
dataWanted[i] = (String)currentData[i][1];
}
If this isn't what you're trying to accomplish, then please edit your question to be more specific.
In my application i got string values dynamically. I want to assign these values to string array then print those values.But it shows an error(Null pointer exception)
EX:
String[] content = null;
for (int s = 0; s < lst.getLength(); s++) {
String st1 = null;
org.w3c.dom.Node nd = lst.item(s);
if (nd.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
NamedNodeMap nnm = nd.getAttributes();
for (int i = 0; i < 1; i++) {
st1 = ((org.w3c.dom.Node) nnm.item(i)).getNodeValue().toString();
}
}
content[s] = st1;
//HERE it shows null pointer Exception.
}
Thanks
This is because your string array is null. String[] content=null;
You declare your array as null and then try to assign values in it and that's why it is showing NPE.
You can try giving initial size to your string array or better to use ArrayList<String>.
ie:
String[] content = new String[10]; //--- You must know the size or array out of bound will be thrown.
Better if you use arrayList like
List<String> content = new ArrayList<String>(); //-- no need worry about size.
For list use add(value) method to add new values in list and use foreach loop to print the content of list.
Use ArrayList or Vector for creating collection (or array) of strings in a dynamic fashion.
List<String> contents = new ArrayList<String>();
Node node = (org.w3c.dom.Node) nnm.item(i)).getNodeValue();
if (null != node)
contents.add(node.toString());
Outside the loop you can do as follows
for(String content : contents) {
System.out.println(content) // since you wanted to print them out
It's a little hard to understand what you're after because your example got munged. However, your String array is null. You need to initialize it, not just declare it. Have you considered using an ArrayList instead? Arrays in java are fixed length (unless they changed this since my university days).
ArrayList is a lot simpler to work with.
E.g.:
List<String> content = new ArrayList<String>();
for (int i = 0; i < limit; i++){
String toAdd;
//do some stuff to get a value into toAdd
content.add(toAdd)
}
There's also something weird with one of your for loops.
for(int i=0;i<1;i++)
The above will only ever iterate once. To clarify:
for(int i=0;i<1;i++){
System.out.println("hello");
}
is functionally identical to:
System.out.println("hello");
They both print out "hello" once, adn that's it.
Use
content[s] = new String(st1);
Now it creates new instance for that particular array index.
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.
This question already has answers here:
Why does the foreach statement not change the element value?
(6 answers)
Closed 5 years ago.
Ok, so I'm tyring to iterate through an ArrayList and remove a specefic element. However, I am having some trouble using the For-Each like structure. When I run the following code:
ArrayList<String> arr = new ArrayList<String>();
//... fill with some values (doesn't really matter)
for(String t : arr)
{
t = " some other value "; //hoping this would change the actual array
}
for(String t : arr)
{
System.out.println(t); //however, I still get the same array here
}
My question in, how can I make 't' a pointer to 'arr' so that I am able to change the values in a for-each loop? I know I could loop through the ArrayList using a different structure, but this one looks so clean and readable, it would just be nice to be able to make 't' a pointer.
All comments are appreciated! Even if you say I should just suck it up and use a different construct.
I think the best approach may be to use a for loop.
ArrayList<String> arr = new ArrayList<String>();
for (int i = 0; i < arr.size(); i++) {
String t = arr.get(i);
if (// your condition is met) {
arr.set(i, "your new value");
}
}
The problem is that you're trying to change the loop-scoped reference t to let it point to a new String instance. This ain't going to work. It does not refer the actual entry in the arraylist. You need to change the actual value of the reference. If String was mutable and provided a fictive set() method for that, you could in theory do
for (String t : arr) {
t.set("some other value");
}
or so, but that's not possible as it is immutable. Better get a handle of the entrypoint in the array itself using the normal for loop:
for (int i = 0; i < arr.size(); i++) {
arr.set(i, "some other value");
}
If you insist in using the enhanced for loop, then you need to replace String by StringBuilder, which is mutable:
for (StringBuilder t : arr) {
t.delete(0, t.length()).append("some other value");
}
Remember, Java is pass-by-value, not pass-by-reference.
For-each doesn't give you an index pointer, so you just can't use it to change an immutable value.
Either use a for-loop with an index or use a mutable type (like StringBuffer, not String)
An array of objects (like strings) in Java is a contiguous block containing an ordered series of references. So, when you have an array of 4 strings, what you really have is 4 references stored IN the array, and 4 string objects that are outside of the array but are referenced by its 4 elements.
What the for-each construct in Java does is create a local variable and, for each iteration, copy into that local variable the reference from the array cell that corresponds to that iteration. When you set the loop variable (t = " some other value") you are putting a reference to a new string, "some other value", into the local variable t, not into the array.
The contrasts with some other languages (like Perl) where the loop variable acts like an alias to the array/list element itself.
Your code is re-written by the compiler as something like this:
ArrayList<String> arr = new ArrayList<String>();
//... fill with some values (doesn't really matter)
for (final Iterator <String> i = arr.iterator(); i.hasNext();) {
String t;
t = i.next();
t = " some other value "; // just changes where t is pointing
}
To do what you want you would have to write the for loop like this:
for (final ListIterator<String> i = arr.iterator(); i.hasNext();) {
final String t;
t = i.next();
i.set("some other value");
}
Iterator does not have the set method, only ListIterator does.
Basically you want to remove the String t from the list arr. Just do a arr.remove(t) and you could be done. But you can't do it while iterating over the same list. You'll get an Exception if you try to modify the list this way.
You have two options:
clone your list, iterate through the clone and remove the 'specific' String from the original list
create a list for delete candidates, add all 'specific' Strings to that list and, after iterating through the original list, iterate through the wastebin and remove everything you've collected here from the original list.
Option 1 is the easist, the clone can be made like:
List<String> clone = new ArrayList<String>(arr);
You seem to misunderstand how objects/references work in Java, which is pretty fundamental to using the language effectively. However, this code here should do what you want (apologies for the lack of explanation):
ArrayList<String> arr = new ArrayList<String>();
//... fill with some values (doesn't really matter)
for(int i = 0; i < arr.size(); i++)
{
arr.set(i, " some other value "); // change the contents of the array
}
for(String t : arr)
{
System.out.println(t);
}
I believe, this is not related to immutable or mutable.
t = " some other value "; //hoping this would change the actual array
t does not hold the reference to actual object. Java copies the value from arraylist and puts that value into t so array list value does not get affect.
HTH
This has been answered well. Still here is my suggestion. The var t inside loop is only visible there. It will not be seen outside the loop. You could do t.set() if it was not String.
Use a StringBuffer rather than plain strings. This way the string within is mutable.
Strings are immutable. If you had a mutable type like StringBuilder/Buffer, you could change the string in your iteration. You do have references, remember.